114

Node.jsを使用してログファイルにデータを追加しようとしていますが、正常に機能していますが、次の行に移動しません。 \n以下の私の関数では機能していないようです。助言がありますか?

function processInput ( text ) 
{     
  fs.open('H://log.txt', 'a', 666, function( e, id ) {
   fs.write( id, text + "\n", null, 'utf8', function(){
    fs.close(id, function(){
     console.log('file is updated');
    });
   });
  });
 }
4

4 に答える 4

182

これをWindowsで実行しているようです(H://log.txtファイルパスを指定)。

\r\nの代わりに使用してみてください\n

正直なところ、\n大丈夫です。ログファイルをメモ帳など、Windows以外の改行を表示しないもので表示している可能性があります。別のビューア/エディタ(ワードパッドなど)で開いてみてください。

于 2012-04-30T13:17:56.870 に答える
112

代わりにos.EOL定数を使用してください。

var os = require("os");

function processInput ( text ) 
{     
  fs.open('H://log.txt', 'a', 666, function( e, id ) {
   fs.write( id, text + os.EOL, null, 'utf8', function(){
    fs.close(id, function(){
     console.log('file is updated');
    });
   });
  });
 }
于 2015-09-18T18:29:01.503 に答える
7

組み合わせを使用\r\nして、ノードjsに新しい行を追加します

  var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
  stream.once('open', function(fd) {
    stream.write(msg+"\r\n");
  });
于 2020-08-29T05:36:46.237 に答える
0

または、 fs.appendFileメソッドを使用することもできます

let content = 'some text';
content += "\n";
fs.appendFile("helloworld.txt", content, (err) => {
    return console.log(err);
});
于 2021-12-27T10:57:19.877 に答える