appenFile不会关闭Node.js中打开的文件

时间:2018-03-17 14:33:54

标签: node.js fs

read fs.appendFile没有返回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在操作后没有关闭文件?

1 个答案:

答案 0 :(得分:2)

您可能知道fs.appendFile是异步的。所以在代码中你同时调用fs.appendFile 10000次。

你需要等待第一个追加完成才能再次追加。

这应该有效:

var index = 0;
function append(){
    fs.appendFile("append.txt", index+ "\n", function (err) {
        index++;
        if (index < 10000)
            append();
        else
            console.log('Done');
    });
};
append();

另请注意,这对性能非常不利。