node.js - opendir 返回 fs.Dir 可通过 promise 进行迭代,但不可通过 Sync 进行迭代。为什么?
问题描述
如果我使用从 fs.promises 导入的 opendir,我可以使用 fs.Dir 作为可迭代的 for ... of。相反,如果我使用 opendirSync (使用相同的算法),脚本将失败并出现错误“fs.Dir is not iterable”
基于承诺:
const {opendir} = require('fs').promises
async function run(){
try {
const dir = await opendir('./');
for await (const dirent of dir)
console.log(dirent.name);
} catch (err) {
console.error(err);
}
}
run()
同步 :
const {opendirSync} = require('fs')
function run(){
try {
const dir = opendirSync('./');
for (const dirent of dir)
console.log(dirent.name);
} catch (err) {
console.error(err);
}
}
run()
解决方案
这里的区别在于您如何处理fs.Dir
对象。
for await (const dirent of dir)
与for (const dirent of dir)
。
它有一个asyncIterator所以它只能用一个for await...of
循环来迭代。
推荐阅读
- ios - 在 SwiftUI 中,如何使手势在容器视图之外处于非活动状态?
- openapi - 打开 api 3 为单个字符串项添加多个随机示例
- python - 通过纬度和经度绘制数据
- python - 我可以将 Pandas 数据框的后续列分配给变量元组吗?
- if-statement - 一千个嵌套的 if/and/or
- r - 带有 URL 的“-`*tmp*` 中的错误:一元运算符的参数无效”
- r - xtable + addcontentsline
- javascript - React 将 props 传递给二级子级
- symfony - symfony 额外的用户信息在认证后保留在会话中
- reactjs - 无法使用 react-pdf 和 react-js 下载 PDF