用nodejs读取许多文件的最佳方法是什么?

我有一大堆的文件path。 我从一个stream式的glob模块https://github.com/wearefractal/glob-stream获取这个path列表

我正在将这个streampipe道传输到另一个为每个path创buildfileReadStreamsstream,并迅速触及一些限制。 我得到:

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

还有Error: EMFILE, open

我已经试过碰到maxListeners但我有9000文件,这将创buildstream,我担心会吃的内存数量是不恒定的,将增长。 我可以安全地删除这里的限制吗?

我应该做同步吗? 或者我应该迭代的path和顺序读取文件? 那么还不能用for循环一次执行所有的读操作吗?

最大的听众是纯粹的警告 。 setMaxListeners只控制消息何时打印到控制台,没有别的。 你可以禁用它或者忽略它。

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

因为通过运行数千个并发的文件系统操作来使磁盘饱和将不会获得任何额外的性能 – 实际上,这会损害,特别是在传统的非SSD驱动器上 – 这是一个好主意,一旦。

我可能会使用asynchronous队列 ,它允许您在一个循环中将每个文件的名称推送到队列中,然后一次只运行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(); }); 

您可能需要尝试一点才能为您的应用程序find正确的并发编号。