使用nodejs读取许多文件的最佳方式

Best way to read many files with nodejs?

本文关键字:最佳 方式 文件 许多 nodejs 读取 使用      更新时间:2023-09-26

我有大量的文件路径。我从流glob模块https://github.com/wearefractal/glob-stream

得到这个路径列表

我将这个流管道到另一个流,该流为每个路径创建fileReadStreams,并很快达到一些限制。我得到了:

warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit

Error: EMFILE, open

我试过碰撞maxListeners,但我有~9000个文件,将创建流,我担心会吃内存,这个数字不是恒定的,会增长。我可以把这里的极限移开吗?

我应该同步地做这个吗?还是应该遍历路径并依次读取文件?这不会使用for循环一次执行所有的读操作吗?

最大监听器的事情纯粹是一个警告。setMaxListeners仅控制何时将该消息打印到控制台,没有其他内容。你可以禁用它或者忽略它。

EMFILE是你的操作系统强制限制进程一次可以拥有的打开文件(文件描述符)的数量。您可以通过使用ulimit增加限制来避免这种情况。

因为通过运行成千上万的并发文件系统操作而使磁盘饱和不会给您带来任何额外的性能——事实上,它会损害性能,特别是在传统的非ssd驱动器上——因此,一次只运行受控数量的操作是一个好主意。

我可能会使用异步队列,它允许您在一个循环中将每个文件的名称推入队列,然后一次只运行n操作。当一个操作完成后,队列中的下一个操作开始。

例如:

var q = async.queue(function (file, cb) {
    var stream = fs.createReadStream(file.path);
    // ...
    stream.on('end', function() {
        // finish up, then
        cb();
    });
}, 2);
globStream.on('data', function(file) {
    q.push(file);
});
globStream.on('end', function() {
    // We don't want to add the `drain` handler until *after* the globstream
    // finishes.  Otherwise, we could end up in a situation where the globber
    // is still running but all pending file read operations have finished.
    q.drain = function() {
        // All done with everything.
    };
    // ...and if the queue is empty when the globber finishes, make sure the done
    // callback gets called.
    if (q.idle()) q.drain();
});

您可能需要稍微试验一下才能找到适合您的应用程序的并发数。