我试图将一个字符串附加到日志文件.但是,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'
Run Code Online (Sandbox Code Playgroud)
知道怎么做这个简单的方法吗?
丹尼尔
den*_*que 721
对于偶尔的附加,您可以使用appendFile
,每次调用时都会创建一个新的文件句柄:
异步:
const fs = require('fs');
fs.appendFile('message.txt', 'data to append', function (err) {
if (err) throw err;
console.log('Saved!');
});
Run Code Online (Sandbox Code Playgroud)
同步:
const fs = require('fs');
fs.appendFileSync('message.txt', 'data to append');
Run Code Online (Sandbox Code Playgroud)
但是如果你反复追加到同一个文件,重用文件句柄要好得多.
Pla*_*ute 176
如果要在日志文件中写入,即将数据附加到文件的末尾,从不使用appendFile
,请appendFile
为添加到文件中的每个数据打开文件句柄,过一会儿就会出现漂亮的EMFILE
错误.
我可以补充一点,这appendFile
比使用起来并不容易WriteStream
.
示例appendFile
:
console.log(new Date().toISOString());
[...Array(10000)].forEach( function (item,index) {
fs.appendFile("append.txt", index+ "\n", function (err) {
if (err) console.log(err);
});
});
console.log(new Date().toISOString());
Run Code Online (Sandbox Code Playgroud)
在我的计算机上最多8000个,你可以将数据附加到文件,然后你得到这个:
{ Error: EMFILE: too many open files, open 'C:\mypath\append.txt'
at Error (native)
errno: -4066,
code: 'EMFILE',
syscall: 'open',
path: 'C:\\mypath\\append.txt' }
Run Code Online (Sandbox Code Playgroud)
此外,appendFile
它将在启用时写入,因此您的日志将不会被时间戳写入.你可以用例子测试,设置1000代替100000,命令将是随机的,取决于对文件的访问.
如果要附加到文件,则必须使用如下可写流:
var stream = fs.createWriteStream("append.txt", {flags:'a'});
console.log(new Date().toISOString());
[...Array(10000)].forEach( function (item,index) {
stream.write(index + "\n");
});
console.log(new Date().toISOString());
stream.end();
Run Code Online (Sandbox Code Playgroud)
你想要的时候结束它.您甚至不需要使用stream.end()
默认选项AutoClose:true
,因此您的文件将在您的流程结束时结束并且您避免打开太多文件.
Fab*_*ari 116
使用createWriteStream的代码为每次写入创建一个文件描述符.log.end更好,因为它要求节点在写入后立即关闭.
var fs = require('fs');
var logStream = fs.createWriteStream('log.txt', {flags: 'a'});
// use {flags: 'a'} to append and {flags: 'w'} to erase and write a new file
logStream.write('Initial line...');
logStream.end('this is the end line');
Run Code Online (Sandbox Code Playgroud)
A J*_*A J 23
此外appendFile
,您还可以传入一个标志writeFile
以将数据附加到现有文件.
fs.writeFile('log.txt', 'Hello Node', {'flag':'a'}, function(err) {
if (err) {
return console.error(err);
}
});
Run Code Online (Sandbox Code Playgroud)
通过传递标记'a',数据将附加在文件的末尾.
Cor*_*art 19
你需要打开它,然后写入它.
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');
});
});
});
Run Code Online (Sandbox Code Playgroud)
以下是一些有助于解释参数的链接
编辑:这个答案不再有效,请查看新的fs.appendFile方法进行追加.
viv*_*wal 18
当您需要将某些内容附加到文件时,使用fs.appendFile
或fsPromises.appendFile
是最快且最强大的选项。
与建议的一些答案相反,如果向函数提供文件路径appendFile
, 它实际上会自行关闭。只有当您传递一个文件句柄时,fs.open()
您才需要关闭它。
我在一个文件中尝试了超过 50,000 行。
例子 :
(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.'
);
})();
Run Code Online (Sandbox Code Playgroud)
参考:https: //github.com/nodejs/node/issues/7560
chb*_*own 13
节点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!');
});
Run Code Online (Sandbox Code Playgroud)
文档:http://nodejs.org/docs/latest/api/fs.html#fs_fs_appendfile_filename_data_encoding_utf8_callback
t_d*_*m93 10
使用a+
标志附加并创建一个文件(如果不存在):
fs.writeFile('log.txt', 'Hello Node', { flag: "a+" }, (err) => {
if (err) throw err;
console.log('The file is created if not existing!!');
});
Run Code Online (Sandbox Code Playgroud)
文档:https : //nodejs.org/api/fs.html#fs_file_system_flags
我的方法比较特殊。我基本上使用了WriteStream
解决方案,但实际上没有通过使用stream.end()
. 相反,我使用cork
/ uncork
。这获得了低 RAM 使用率的好处(如果这对任何人都很重要),我相信用于日志记录/记录(我的原始用例)更安全。
下面是一个非常简单的例子。请注意,我刚刚for
为展示添加了一个伪循环——在生产代码中,我正在等待 websocket 消息。
var stream = fs.createWriteStream("log.txt", {flags:'a'});
for(true) {
stream.cork();
stream.write("some content to log");
process.nextTick(() => stream.uncork());
}
Run Code Online (Sandbox Code Playgroud)
uncork
将在下一个滴答中将数据刷新到文件中。
在我的场景中,各种大小的峰值高达每秒约 200 次写入。然而,在夜间,每分钟只需要少量写入。即使在高峰时段,该代码也能非常可靠地工作。
fd = fs.openSync(path.join(process.cwd(), 'log.txt'), 'a')
fs.writeSync(fd, 'contents to append')
fs.closeSync(fd)
Run Code Online (Sandbox Code Playgroud)
如果您想要一种简单无压力的方式在文件中逐行写入日志,那么我推荐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');
Run Code Online (Sandbox Code Playgroud)
使用 Node v8.9.4 测试。
归档时间: |
|
查看次数: |
413752 次 |
最近记录: |