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

有什么简单的方法吗?


当前回答

我提供这个建议只是因为控制打开标志有时是有用的,例如,你可能想先截断一个现有的文件,然后追加一系列的写入-在这种情况下,打开文件时使用'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!');
      });
    });
  });

其他回答

尝试使用flags: 'a'将数据附加到文件中

 var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
  stream.once('open', function(fd) {
    stream.write(msg+"\r\n");
  });

Node.js 0.8有fs.appendFile:

fs.appendFile('message.txt', 'data to append', (err) => {
  if (err) throw err;
  console.log('The "data to append" was appended to file!');
});

文档

使用fs。appendFile或fsPromises。当您需要向文件中追加内容时,appendFile是最快和最健壮的选项。

与建议的一些答案相反,如果文件路径提供给appendFile函数,它实际上会自行关闭。只有传入fs.open()之类的文件句柄时,才需要注意关闭它。

我在一个超过5万行的文件中试过。

例子:

(async () => {
  // using appendFile.
  const fsp = require('fs').promises;
  await fsp.appendFile(
    '/path/to/file', '\r\nHello world.'
  );

  // using apickfs; handles error and edge cases better.
  const apickFileStorage = require('apickfs');
  await apickFileStorage.writeLines(
    '/path/to/directory/', 'filename', 'Hello world.'
  );
})();

裁判:https://github.com/nodejs/node/issues/7560

const inovioLogger = (logger = "") => {
    const log_file = fs.createWriteStream(__dirname + `/../../inoviopay-${new Date().toISOString().slice(0, 10)}.log`, { flags: 'a' });
    const log_stdout = process.stdout;
    log_file.write(logger + '\n');
}

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

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);