首页 > 解决方案 > NodeJS:关于异步“readdir”和“stat”的混淆

问题描述

在文档中,它显示了readdirstat的两个版本。两者都有异步和同步版本readir/readdirSyncstat/statSync.

因为readidirandstat是异步的,我希望它们返回一个 Promise 但是当尝试使用async/await脚本时不会等待readdir解决,如果我使用.then/.catch我会得到一个错误cannot read .then of undefined

我在这里要做的就是将运行脚本的目录中存在的目录映射到dirsOfCurrentDir地图中。

返回错误cannot read .then of undefined

const fs = require('fs');

const directory = `${ __dirname }/${ process.argv[2] }`;
const dirsOfCurrentDir = new Map();

fs.readdir(directory, (err, files) => {
  let path;

  if (err)
    return console.log(err);

  files.forEach(file => {
    path = directory + file;

    fs.stat(path, (err, stats) => {
      if (err)
        return console.log(err);

      dirsOfCurrentDir.set(file, directory);
    });
  });
}).then(() => console.log('adasdasd'))

console.log(dirsOfCurrentDir)

退货Map {}

const foo = async () => {
  await fs.readdir(directory, (err, files) => {
    let path;

    if (err)
      return console.log(err);

    files.forEach(file => {
      path = directory + file;

      fs.stat(path, (err, stats) => {
        if (err)
          return console.log(err);

        dirsOfCurrentDir.set(file, directory);
      });
    });
  });
};

foo()
console.log(dirsOfCurrentDir)

编辑

我最终选择了这两个函数的同步版本,readdirSync并且statSync. 虽然使用 async 方法或 promisify 会感觉更好,但我仍然没有弄清楚如何让我的代码使用其中任何一种方法正常工作。

const fs = require('fs');

const directory = `${ __dirname }/${ process.argv[2] }`;
const dirsOfCurrentDir = new Map();

const dirContents = fs.readdirSync(directory);

dirContents.forEach(file => {
  const path = directory + file;
  const stats = fs.statSync(path);

  if (stats.isDirectory())
    dirsOfCurrentDir.set(file, path);
});

console.log(dirsOfCurrentDir); // logs out the map with all properties set

标签: node.jsasynchronouspromisefs

解决方案


因为 readidir 和 stat 是异步的,我希望它们返回一个 Promise

首先,确保你知道异步函数和async函数之间的区别。在 Javascript 中声明为async使用该特定关键字的函数,例如:

async function foo() {
    ...
}

async总是返回一个承诺(根据使用关键字声明的函数的定义)。

但是诸如异步函数之类的fs.readdir()可能会也可能不会返回一个承诺,这取决于其内部设计。在这种特殊情况下,node.js 中模块的原始实现fs仅使用回调,而不是 Promise(它的设计早于 node.js 中 Promise 的存在)。它的函数是异步的,但没有声明为async,因此它使用常规回调,而不是 Promise。

因此,您必须使用回调或“promisify”接口将其转换为返回承诺的东西,以便您可以使用await它。

node.js v10中有一个实验性接口,它为 fs 模块提供了内置的 Promise。

const fsp = require('fs').promises;

fsp.readdir(...).then(...)

在 node.js 的早期版本中,有很多选项可用于承诺功能。您可以使用util.promisify()逐个函数完成它:

const promisify = require('util').promisify;
const readdirP = promisify(fs.readdir);
const statP = promisify(fs.stat);

由于我还没有在 node v10 上进行开发,所以我经常使用 Bluebird Promise 库并一次性 Promisify 整个 fs 库:

const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));

fs.readdirAsync(...).then(...)

要仅列出给定目录中的子目录,您可以这样做:

const fs = require('fs');
const path = require('path');
const promisify = require('util').promisify;
const readdirP = promisify(fs.readdir);
const statP = promisify(fs.stat);

const root = path.join(__dirname, process.argv[2]);

// utility function for sequencing through an array asynchronously
function sequence(arr, fn) {
    return arr.reduce((p, item) => {
        return p.then(() => {
            return fn(item);
        });
    }, Promise.resolve());
}

function listDirs(rootDir) {
    const dirsOfCurrentDir = new Map();
    return readdirP(rootDir).then(files => {
        return sequence(files, f => {
            let fullPath = path.join(rootDir, f);
            return statP(fullPath).then(stats => {
                if (stats.isDirectory()) {
                    dirsOfCurrentDir.set(f, rootDir)
                }
            });
        });
    }).then(() => {
        return dirsOfCurrentDir;
    });  
}

listDirs(root).then(m => {
    for (let [f, dir] of m) {
        console.log(f);
    }
});

这是一个更通用的实现,它列出了文件并为列出的内容和如何呈现结果提供了几个选项:

const fs = require('fs');
const path = require('path');
const promisify = require('util').promisify;
const readdirP = promisify(fs.readdir);
const statP = promisify(fs.stat);

const root = path.join(__dirname, process.argv[2]);

// options takes the following:
//     recurse: true | false - set to true if you want to recurse into directories (default false)
//     includeDirs: true | false - set to true if you want directory names in the array of results
//     sort: true | false - set to true if you want filenames sorted in alpha order
//     results: can have any one of the following values
//              "arrayOfFilePaths" - return an array of full file path strings for files only (no directories included in results)
//              "arrayOfObjects" - return an array of objects {filename: "foo.html", rootdir: "//root/whatever", full: "//root/whatever/foo.html"}

// results are breadth first

// utility function for sequencing through an array asynchronously
function sequence(arr, fn) {
    return arr.reduce((p, item) => {
        return p.then(() => {
            return fn(item);
        });
    }, Promise.resolve());
}

function listFiles(rootDir, opts = {}, results = []) {
    let options = Object.assign({recurse: false, results: "arrayOfFilePaths", includeDirs: false, sort: false}, opts);

    function runFiles(rootDir, options, results) {
        return readdirP(rootDir).then(files => {
            let localDirs = [];
            if (options.sort) {
                files.sort();
            }
            return sequence(files, fname => {
                let fullPath = path.join(rootDir, fname);
                return statP(fullPath).then(stats => {
                    // if directory, save it until after the files so the resulting array is breadth first
                    if (stats.isDirectory()) {
                        localDirs.push({name: fname, root: rootDir, full: fullPath, isDir: true});
                    } else {
                        results.push({name: fname, root: rootDir, full: fullPath, isDir: false});
                    }
                });
            }).then(() => {
                // now process directories
                if (options.recurse) {
                    return sequence(localDirs, obj => {
                        // add directory to results in place right before its files
                        if (options.includeDirs) {
                            results.push(obj);
                        }
                        return runFiles(obj.full, options, results);
                    });
                } else {
                    // add directories to the results (after all files)
                    if (options.includeDirs) {
                        results.push(...localDirs);
                    }
                }
            });
        });
    }

    return runFiles(rootDir, options, results).then(() => {
        // post process results based on options
        if (options.results === "arrayOfFilePaths") {
            return results.map(item => item.full);
        } else {
            return results;
        }
    });
}

// get flat array of file paths, 
//     recursing into directories, 
//     each directory sorted separately
listFiles(root, {recurse: true, results: "arrayOfFilePaths", sort: true, includeDirs: false}).then(list => {
    for (const f of list) {
        console.log(f);
    }
}).catch(err => {
    console.log(err);
});

您可以将此代码复制到文件中并运行它,.作为参数传递以列出脚本的目录或您要列出的任何子目录名称。

如果您想要更少的选项(例如没有递归或不保留目录顺序),则可以显着减少此代码,并且可能会更快一些(并行运行一些异步操作)。


推荐阅读