appenFile 不会关闭 Node.js 中打开的文件
appenFile doesnt close opened files in Node.js
我 read fs.appendFile
没有 return fd
(文件描述符),因此它可以打开文件甚至为您关闭。但是在下面的例子中我得到了错误
Error: EMFILE: too many open files, open
[...Array(10000)].forEach( function (item,index) {
fs.appendFile("append.txt", index+ "\n", function (err) {
if (err) console.log(err);
})});
我认为这意味着对于每个新的追加,它都会一遍又一遍地打开同一个文件。
但是,对于流,一切都很好
var stream = fs.createWriteStream("append.txt", {flags:'a'});
[...Array(10000)].forEach( function (item,index) {
stream.write(index + "\n")});
那么,为什么在第一种情况下appendFile在操作后没有关闭文件呢?
如您所知,fs.appendFile 是异步的。所以在代码中你同时调用了fs.appendFile10000次
您只需等待第一个追加完成,然后再追加。
这应该有效:
var index = 0;
function append(){
fs.appendFile("append.txt", index+ "\n", function (err) {
index++;
if (index < 10000)
append();
else
console.log('Done');
});
};
append();
另请注意,这对性能非常不利。
我 read fs.appendFile
没有 return fd
(文件描述符),因此它可以打开文件甚至为您关闭。但是在下面的例子中我得到了错误
Error: EMFILE: too many open files, open
[...Array(10000)].forEach( function (item,index) {
fs.appendFile("append.txt", index+ "\n", function (err) {
if (err) console.log(err);
})});
我认为这意味着对于每个新的追加,它都会一遍又一遍地打开同一个文件。 但是,对于流,一切都很好
var stream = fs.createWriteStream("append.txt", {flags:'a'});
[...Array(10000)].forEach( function (item,index) {
stream.write(index + "\n")});
那么,为什么在第一种情况下appendFile在操作后没有关闭文件呢?
如您所知,fs.appendFile 是异步的。所以在代码中你同时调用了fs.appendFile10000次
您只需等待第一个追加完成,然后再追加。
这应该有效:
var index = 0;
function append(){
fs.appendFile("append.txt", index+ "\n", function (err) {
index++;
if (index < 10000)
append();
else
console.log('Done');
});
};
append();
另请注意,这对性能非常不利。