【问题标题】:appenFile doesnt close opened files in Node.jsappenFile 不会关闭 Node.js 中打开的文件
【发布时间】:2018-03-17 23:51:37
【问题描述】:

我已经 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 在操作后没有关闭文件?

【问题讨论】:

    标签: node.js fs


    【解决方案1】:

    您可能知道 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();
    

    还要注意这对性能非常不利。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 2013-07-09
      • 2018-01-27
      相关资源
      最近更新 更多