我试图追加一个字符串到日志文件。但是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。appendFile或fsPromises。当您需要向文件中追加内容时,appendFile是最快和最健壮的选项。
与建议的一些答案相反,如果文件路径提供给appendFile函数,它实际上会自行关闭。只有传入fs.open()之类的文件句柄时,才需要注意关闭它。
我在一个超过5万行的文件中试过。
例子:
(async () => {
// using appendFile.
const fsp = require('fs').promises;
await fsp.appendFile(
'/path/to/file', '\r\nHello world.'
);
// using apickfs; handles error and edge cases better.
const apickFileStorage = require('apickfs');
await apickFileStorage.writeLines(
'/path/to/directory/', 'filename', 'Hello world.'
);
})();
裁判:https://github.com/nodejs/node/issues/7560
其他回答
我包装了async fs。appendFile变成一个基于promise的函数。希望它能帮助其他人看到这是如何运作的。
append (path, name, data) {
return new Promise(async (resolve, reject) => {
try {
fs.appendFile((path + name), data, async (err) => {
if (!err) {
return resolve((path + name));
} else {
return reject(err);
}
});
} catch (err) {
return reject(err);
}
});
}
如果你想要一种简单而无压力的方法在文件中逐行写入日志,那么我推荐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测试。
你需要打开它,然后写进去。
var fs = require('fs'), str = 'string to append to file';
fs.open('filepath', 'a', 666, function( e, id ) {
fs.write( id, 'string to append to file', null, 'utf8', function(){
fs.close(id, function(){
console.log('file closed');
});
});
});
下面是一些有助于解释参数的链接
开放 写 关闭
编辑:这个答案不再有效,请查看新的fs。appendFile追加方法。
使用jfile包:
myFile.text+='\nThis is new line to be appended'; //myFile=new JFile(path);
我提供这个建议只是因为控制打开标志有时是有用的,例如,你可能想先截断一个现有的文件,然后追加一系列的写入-在这种情况下,打开文件时使用'w'标志,直到所有写入完成才关闭它。当然,appendFile可能是你想要的:-)
fs.open('log.txt', 'a', function(err, log) {
if (err) throw err;
fs.writeFile(log, 'Hello Node', function (err) {
if (err) throw err;
fs.close(log, function(err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
});