在Node JS中使用Promise的递归目录列表

时间:2018-09-05 16:44:28

标签: node.js es6-promise readdir

我想使用node.js中的 promises 递归列出目录并读取其中的文件。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

给出以下目录结构:

-l<library-name>

您有几种方法可以做到这一点。让我们考虑使用. ├── dirtest │   ├── bar.txt │   └── foo │   └── foo.txt └── index.js / async进行布局最容易的方法,注释在代码中:

await

这将产生带有路径前缀的文件嵌套数组:

const fs = require("fs");
const path = require("path");
const util = require("util");

// Promisify the fs functions we will use (or use require("fs").promises)
const astat = util.promisify(fs.stat);
const areaddir = util.promisify(fs.readdir);

/**
 * Get a list of all files in a directory
 * @param {String} dir The directory to inventory
 * @returns {Array} Array of files
 */
async function getFiles(dir) {
  // Get this directory's contents
  const files = await areaddir(dir);
  // Wait on all the files of the directory
  return Promise.all(files
    // Prepend the directory this file belongs to
    .map(f => path.join(dir, f))
    // Iterate the files and see if we need to recurse by type
    .map(async f => {
      // See what type of file this is
      const stats = await astat(f);
      // Recurse if it is a directory, otherwise return the filepath
      return stats.isDirectory() ? getFiles(f) : f;
    }));
}

getFiles(".")
  .then(files => JSON.stringify(files, null, 4))
  .then(console.log)
  .catch(console.error);

然后您可以通过从以下问题中提取内容来扩充此文件:Merge/flatten an array of arrays in JavaScript?

[
    [
        "dirtest/bar.txt",
        [
            "dirtest/foo/foo.txt"
        ]
    ],
    "index.js"
]

哪个会产生:

/**
 * Flatten an arbitrarrily deep Array of Arrays to a single Array
 * @param {Array} arr Array of Arrays to flatten
 * @returns {Array} The flattened Array
 */
function flatten(arr) {
  return arr.reduce((flat, toFlatten) => flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten), []);
}

/*
 * Same code from above snippet
 */

getFiles(".")
  .then(flatten)
  .then(files => JSON.stringify(files, null, 4))
  .then(console.log)
  .catch(console.error);
相关问题