javascript - 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
}
推荐阅读
- flutter - 如何在flutter中订购从firestore中检索到的数据?
- javascript - 为什么我的 wordpress ajax 没有在前端 javascript 文件中调用?
- php - Web 和 CLI mysql 不会同时连接
- python - 是否可以在不使用 Python 执行任何代码的情况下获得代码覆盖率?
- angular - 当我想创建新项目时,Angular/CLI 出现错误
- sql - 内部连接表 A 和 B 返回 50 行。左连接 B 到 A 返回 125 行。这里发生了什么?
- node.js - 将 React 应用程序的内容移动到另一个文件夹后出现 npm 启动错误
- python-camelot - 多页pdf上的不同table_areas
- python - 交互 Python 笔记本/组件的概念(例如,用于多智能体强化学习) - 类似 EJB-bean 的组件?
- python - TS SS 矢量相似度使用矩阵