我正在尝试追加一个字符串到日志文件。但是 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');
但是如果你重复追加到同一个文件中,reuse the file handle 会好很多。 .
关于javascript - 如何追加到 Node 中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3459476/