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++;
});
});

我想知道是否有一个缓存正在耗尽,或者我是否应该在每次"结束"后销毁缓冲区,但我读到的任何内容都没有表明这一点,即使我尝试过,也没有什么不同。很多例子都希望你把它放在某个地方,但我不是。在完整的代码中,它创建完整文件的哈希,并将其添加到每个本地文件的对象中。

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

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
}

最新更新