我在尝试着append日志文件中的字符串。但是 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');
但如果您重复附加到同一个文件,最好重用文件句柄.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)