我有一个日志文件,我正在其中添加文本。
这是代码:
function appendText(text) {
fs.writeFile('file.log', text+'\n', {'flag':'a'}, (err) => {
if (err) {
return console.error(err);
}
console.log('Saved!');
});
}
用法:
appendText('some text here');
我的问题是,它没有将文本添加到文件内容末尾的新行中,而是将所有内容添加为一行。
我该如何解决这个问题?
最佳答案
使用appendfile()方法而不是像这样的writeFile(),并使用\r\n而不是仅仅\n。
const fs = require('fs');
function appendText(text) {
fs.appendFile("test", `${text}\r\n`, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
}
appendText("hello");
关于javascript - Node fs.writefile\n 未将文本添加到新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55919721/