首页 > 解决方案 > 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()

标签: node.js

解决方案


这里的区别在于您如何处理fs.Dir对象。

for await (const dirent of dir)for (const dirent of dir)

它有一个asyncIterator所以它只能用一个for await...of循环来迭代。


推荐阅读