首页 > 解决方案 > fs.createReadStream 循环未完成

问题描述

我正在遍历一个包含本地文件的对象,所有这些文件都肯定存在,将它们读入缓冲区并在每个完成时递增一个计数器。问题是尽管有 319 个文件要读取,但很少(如果有的话)将计数器打印到控制台,显示它通过了所有文件。它神秘地停在 200 的某个地方……每次都不同,而且没有抛出任何错误。

我在一个电子项目中运行它,构建的应用程序在 Mac 上无缝运行,但在 Windows 上无法通过这个循环!我最近更新了所有的软件包,并在其他方面进行了必要的调整,整个应用程序运行良好.. 除了这个,它让我发疯!

这是代码:

$.each(compare_object, function(key, item) {
    console.log(item.local_path); // this correctly prints out every single file path
    var f = fs.createReadStream(item.local_path);

    f.on('data', function(buf) {
        // normally some other code goes in here but I've simplified it right down for the purposes of getting it working!
    });

    f.on('end', function(err) {
        num++;
        console.log(num); // this rarely reached past 280 out of 319 files. Always different though.
    });

    f.on('error', function(error) {
        console.log(error); // this never fires.
        num++;
    });
});

我想知道是否有一个缓存最大化,或者我是否应该在每次“结束”之后销毁缓冲区,但我读过的任何内容都没有暗示这一点,即使我尝试过也没有任何区别。很多示例都希望您将其管道传输到某个地方,而我不是。在完整代码中,它创建完整文件的哈希并将其添加到每个本地文件的对象中。

标签: javascriptjquerynode.jselectron

解决方案


我相信循环在这里完成。问题:您正在放置一些异步处理程序。这里最简单的解决方案是在没有流的情况下重写您的代码。

const fs = require('fs')
const util = require('util')


const asyncReadFile = util.promisify(fs.readFile)

//.. this loop goes into some function with async or you can use readFileAsync
for (let [key, item] of Object.entries(compare_object)) {
  const data = await asyncReadFile(item.local_path)
  ///. here goes data handling
}

推荐阅读