我试图追加一个字符串到日志文件。但是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'

有什么简单的方法吗?


当前回答

对于偶尔的追加,你可以使用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');

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

其他回答

fd = fs.openSync(path.join(process.cwd(), 'log.txt'), 'a')
fs.writeSync(fd, 'contents to append')
fs.closeSync(fd)

对于偶尔的追加,你可以使用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');

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

除了appendFile,您还可以在writeFile中传递一个标志来将数据追加到现有文件。

fs.writeFile('log.txt', 'Hello Node',  {'flag':'a'},  function(err) {
    if (err) {
        return console.error(err);
    }
});

通过传递标志'a',数据将被追加到文件的末尾。

使用jfile包:

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

这是完整的脚本。填写您的文件名并运行它,它应该工作! 这里有一个关于脚本背后逻辑的视频教程。

var fs = require('fs');

function ReadAppend(file, appendFile){
  fs.readFile(appendFile, function (err, data) {
    if (err) throw err;
    console.log('File was read');

    fs.appendFile(file, data, function (err) {
      if (err) throw err;
      console.log('The "data to append" was appended to file!');

    });
  });
}
// edit this with your file names
file = 'name_of_main_file.csv';
appendFile = 'name_of_second_file_to_combine.csv';
ReadAppend(file, appendFile);