node.js 如何附加到Node中的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3459476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append to a file in Node?
提问by supercobra
I am trying to appenda string to a log file. However writeFile will erase the content each time before writing the string.
我正在尝试将字符串附加到日志文件中。但是 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'
Any idea how to do this the easy way?
知道如何以简单的方式做到这一点吗?
回答by denysonique
For occasional appends, you can use appendFile, which creates a new file handle each time it's called:
对于偶尔的追加,您可以使用appendFile,它会在每次调用时创建一个新的文件句柄:
异步:
const fs = require('fs');
fs.appendFile('message.txt', 'data to append', function (err) {
if (err) throw err;
console.log('Saved!');
});
同步:
const fs = require('fs');
fs.appendFileSync('message.txt', 'data to append');
But if you append repeatedly to the same file, it's much better to reuse the file handle.
但是如果你重复追加到同一个文件,重用文件句柄会好得多。
回答by Plaute
When you want to write in a log file, i.e. appending data to the end of a file, neveruse appendFile. appendFileopens a file handle for each piece of data you add to your file, after a while you get a beautiful EMFILEerror.
当您想写入日志文件时,即将数据附加到文件末尾时,切勿使用appendFile. appendFile为您添加到文件中的每条数据打开一个文件句柄,一段时间后您会收到一个漂亮的EMFILE错误。
I can add that appendFileis not easier to use than a WriteStream.
我可以补充一点,appendFile它并不比WriteStream.
Example with appendFile:
示例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());
Up to 8000 on my computer, you can append data to the file, then you obtain this:
在我的电脑上最多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' }
Moreover, appendFilewill write when it is enabled, so your logs will not be written by timestamp. You can test with example, set 1000 in place of 100000, order will be random, depends on access to file.
此外,appendFile启用时会写入,因此您的日志不会按时间戳写入。您可以通过示例进行测试,设置 1000 代替 100000,顺序将是随机的,取决于对文件的访问。
If you want to append to a file, you mustuse a writable stream like this:
如果要附加到文件,则必须使用像这样的可写流:
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();
You end it when you want. You are not even required to use stream.end(), default option is AutoClose:true, so your file will end when your process ends and you avoid opening too many files.
你在你想要的时候结束它。您甚至不需要使用stream.end(),默认选项是AutoClose:true,因此您的文件将在您的进程结束时结束,并且您可以避免打开太多文件。
回答by Fabio Ferrari
Your code using createWriteStream creates a file descriptor for every write. log.end is better because it asks node to close immediately after the write.
您使用 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');
回答by A J 9
Besides appendFile, you can also pass a flag in writeFileto append data to an existing file.
此外appendFile,您还可以传入一个标志writeFile以将数据附加到现有文件中。
fs.writeFile('log.txt', 'Hello Node', {'flag':'a'}, function(err) {
if (err) {
return console.error(err);
}
});
By passing flag 'a', data will be appended at the end of the file.
通过传递标志'a',数据将被附加到文件的末尾。
回答by Corey Hart
You need to open it, then write to it.
你需要打开它,然后写入它。
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');
});
});
});
Here's a few links that will help explain the parameters
这是一些有助于解释参数的链接
EDIT: This answer is no longer valid, look into the new fs.appendFilemethod for appending.
编辑:此答案不再有效,请查看用于追加的新fs.appendFile方法。
回答by chbrown
Node.js 0.8 has fs.appendFile:
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!');
});
回答by Luis R.
fd = fs.openSync(path.join(process.cwd(), 'log.txt'), 'a')
fs.writeSync(fd, 'contents to append')
fs.closeSync(fd)
回答by Benny Neugebauer
If you want an easy and stress-free way to write logs line by line in a file, then I recommend fs-extra:
如果您想要一种简单无压力的方式在文件中逐行写入日志,那么我推荐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');
Tested with Node v8.9.4.
使用 Node v8.9.4 测试。
回答by Abdennour TOUMI
回答by vivek agarwal
Using fs.appendFileor fsPromises.appendFileare the fastest and the most robust options when you need to append something to a file.
当您需要将某些内容附加到文件时,使用fs.appendFile或fsPromises.appendFile是最快和最强大的选项。
In contrast to some of the answers suggested, if the file path is supplied to the appendFilefunction, It actually closes by itself. Only when you pass in a filehandle that you get by something like fs.open()you have to take care of closing it.
与建议的某些答案相反,如果将文件路径提供给appendFile函数, 它实际上会自行关闭。只有当您传入一个文件句柄时,您才fs.open()需要注意关闭它。
I tried it with over 50,000 lines in a file.
我在一个文件中尝试了超过 50,000 行。
Examples :
例子 :
(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.'
);
})();
Ref: https://github.com/nodejs/node/issues/7560
Example Execution: https://github.com/apickjs/apickFS/blob/master/writeLines.js
参考:https: //github.com/nodejs/node/issues/7560
示例执行:https: //github.com/apickjs/apickFS/blob/master/writeLines.js


