我试图追加一个字符串到日志文件。但是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'
有什么简单的方法吗?
当前回答
我提供这个建议只是因为控制打开标志有时是有用的,例如,你可能想先截断一个现有的文件,然后追加一系列的写入-在这种情况下,打开文件时使用'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!');
});
});
});
其他回答
这是完整的脚本。填写您的文件名并运行它,它应该工作! 这里有一个关于脚本背后逻辑的视频教程。
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!');
});
文档
我的方法相当特别。我基本上使用WriteStream解决方案,但实际上没有使用stream.end()“关闭”fd。相反,我用软木塞/打开软木塞。这样做的好处是RAM使用率低(如果这对任何人来说都很重要的话),而且我相信它用于日志/记录更安全(我最初的用例)。
下面是一个非常简单的例子。注意,我刚刚为showcase添加了一个伪for循环——在产品代码中,我正在等待websocket消息。
var stream = fs.createWriteStream("log.txt", {flags:'a'});
for(true) {
stream.cork();
stream.write("some content to log");
process.nextTick(() => stream.uncork());
}
Uncork将在下一个标记中将数据刷新到文件中。
在我的场景中,各种大小的峰值每秒可达~200次写入。但是在夜间,每分钟只需要少量的写入。即使在高峰时段,代码也非常可靠。
我提供这个建议只是因为控制打开标志有时是有用的,例如,你可能想先截断一个现有的文件,然后追加一系列的写入-在这种情况下,打开文件时使用'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!');
});
});
});