我试图追加一个字符串到日志文件。但是writeFile会在每次写入字符串之前删除内容。

fs.writeFile('log.txt', 'Hello Node', function (err) {
  if (err) throw err;
  console.log('It\'s saved!');
}); // => message.txt erased, contains only 'Hello Node'

有什么简单的方法吗?


当前回答

使用jfile包:

myFile.text+='\nThis is new line to be appended'; //myFile=new JFile(path);

其他回答

你需要打开它,然后写进去。

var fs = require('fs'), str = 'string to append to file';
fs.open('filepath', 'a', 666, function( e, id ) {
  fs.write( id, 'string to append to file', null, 'utf8', function(){
    fs.close(id, function(){
      console.log('file closed');
    });
  });
});

下面是一些有助于解释参数的链接

开放 写 关闭


编辑:这个答案不再有效,请查看新的fs。appendFile追加方法。

我提供这个建议只是因为控制打开标志有时是有用的,例如,你可能想先截断一个现有的文件,然后追加一系列的写入-在这种情况下,打开文件时使用'w'标志,直到所有写入完成才关闭它。当然,appendFile可能是你想要的:-)

  fs.open('log.txt', 'a', function(err, log) {
    if (err) throw err;
    fs.writeFile(log, 'Hello Node', function (err) {
      if (err) throw err;
      fs.close(log, function(err) {
        if (err) throw err;
        console.log('It\'s saved!');
      });
    });
  });

使用createWriteStream的代码为每次写入创建一个文件描述符。日志。End更好,因为它要求节点在写入后立即关闭。

var fs = require('fs');
var logStream = fs.createWriteStream('log.txt', {flags: 'a'});
// use {flags: 'a'} to append and {flags: 'w'} to erase and write a new file
logStream.write('Initial line...');
logStream.end('this is the end line');

对于偶尔的追加,你可以使用appendFile,每次调用它都会创建一个新的文件句柄:

异步:

const fs = require('fs');

fs.appendFile('message.txt', 'data to append', function (err) {
  if (err) throw err;
  console.log('Saved!');
});

同步:

const fs = require('fs');

fs.appendFileSync('message.txt', 'data to append');

但如果重复向同一个文件追加,重用文件句柄会好得多。

使用jfile包:

myFile.text+='\nThis is new line to be appended'; //myFile=new JFile(path);