如何在Node中附加文件? [英] How to append to a file in Node?
本文介绍了如何在Node中附加文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将字符串追加到日志文件.但是writeFile每次写入字符串之前都会擦除内容.
I am trying to append a string to a log file. However writeFile will erase the content each time before writing the string.
fs.writeFile('log.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
}); // => message.txt erased, contains only 'Hello Node'
有什么想法可以轻松实现吗?
Any idea how to do this the easy way?
推荐答案
对于偶尔的追加,您可以使用appendFile
,每次调用它时都会创建一个新的文件句柄:
For occasional appends, you can use appendFile
, which creates a new file handle each time it's called:
异步:
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');
But if you append repeatedly to the same file, it's much better to reuse the file handle.
这篇关于如何在Node中附加文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文