我试图追加一个字符串到日志文件。但是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.writeFile('log.txt', 'Hello Node', { flag: "a+" }, (err) => {
if (err) throw err;
console.log('The file is created if not existing!!');
});
文档:https://nodejs.org/api/fs.html # fs_file_system_flags
其他回答
使用+标记追加并创建一个文件(如果不存在):
fs.writeFile('log.txt', 'Hello Node', { flag: "a+" }, (err) => {
if (err) throw err;
console.log('The file is created if not existing!!');
});
文档:https://nodejs.org/api/fs.html # fs_file_system_flags
除了appendFile,您还可以在writeFile中传递一个标志来将数据追加到现有文件。
fs.writeFile('log.txt', 'Hello Node', {'flag':'a'}, function(err) {
if (err) {
return console.error(err);
}
});
通过传递标志'a',数据将被追加到文件的末尾。
这是完整的脚本。填写您的文件名并运行它,它应该工作! 这里有一个关于脚本背后逻辑的视频教程。
var fs = require('fs');
function ReadAppend(file, appendFile){
fs.readFile(appendFile, function (err, data) {
if (err) throw err;
console.log('File was read');
fs.appendFile(file, data, function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
});
}
// edit this with your file names
file = 'name_of_main_file.csv';
appendFile = 'name_of_second_file_to_combine.csv';
ReadAppend(file, appendFile);
如果你想要一种简单而无压力的方法在文件中逐行写入日志,那么我推荐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测试。
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!');
});
文档