我试图追加一个字符串到日志文件。但是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'
有什么简单的方法吗?
我试图追加一个字符串到日志文件。但是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'
有什么简单的方法吗?
当前回答
使用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
其他回答
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!');
});
文档
除了appendFile,您还可以在writeFile中传递一个标志来将数据追加到现有文件。
fs.writeFile('log.txt', 'Hello Node', {'flag':'a'}, function(err) {
if (err) {
return console.error(err);
}
});
通过传递标志'a',数据将被追加到文件的末尾。
对于偶尔的追加,你可以使用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');
但如果重复向同一个文件追加,重用文件句柄会好得多。
如果你想要一种简单而无压力的方法在文件中逐行写入日志,那么我推荐fs-extra:
const os = require('os');
const fs = require('fs-extra');
const file = 'logfile.txt';
const options = {flag: 'a'};
async function writeToFile(text) {
await fs.outputFile(file, `${text}${os.EOL}`, options);
}
writeToFile('First line');
writeToFile('Second line');
writeToFile('Third line');
writeToFile('Fourth line');
writeToFile('Fifth line');
使用Node v8.9.4测试。
尝试使用flags: 'a'将数据附加到文件中
var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
stream.once('open', function(fd) {
stream.write(msg+"\r\n");
});