javascript [node.js 8+]递归获取目录中的所有文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript [node.js 8+]递归获取目录中的所有文件相关的知识,希望对你有一定的参考价值。

// Node 8+
// --------------------------------------------------------------
// No external dependencies

const { promisify } = require('util');
const { resolve } = require('path');
const fs = require('fs');
const readdir = promisify(fs.readdir);
const stat = promisify(fs.stat);

async function getFiles(dir) {
  const subdirs = await readdir(dir);
  const files = await Promise.all(subdirs.map(async (subdir) => {
    const res = resolve(dir, subdir);
    return (await stat(res)).isDirectory() ? getFiles(res) : res;
  }));
  return files.reduce((a, f) => a.concat(f), []);
}

// Usage

getFiles(__dirname)
  .then(files => console.log(files))
  .catch(e => console.error(e));


// Node 10.10+
// --------------------------------------------------------------
// Updated for node 10+ with even more whizbang:

const { resolve } = require('path');
const { readdir } = require('fs').promises;

async function getFiles(dir) {
  const dirents = await readdir(dir, { withFileTypes: true });
  const files = dirents.map((dirent) => {
    const res = resolve(dir, dirent.name);
    return dirent.isDirectory() ? getFiles(res) : res;
  });
  return Array.prototype.concat(...files);
}

// Note that starting with node 11.15.0 you can use 
// `files.flat()` instead of `Array.prototype.concat(...files)` 
// to flatten the array.


// Node 11+
// --------------------------------------------------------------
// The following version uses async iterators.

const { resolve } = require('path');
const { readdir } = require('fs').promises;

async function* getFiles(dir) {
  const dirents = await readdir(dir, { withFileTypes: true });
  for (const dirent of dirents) {
    const res = resolve(dir, dirent.name);
    if (dirent.isDirectory()) {
      yield* getFiles(res);
    } else {
      yield res;
    }
  }
}

// Usage has changed because the return type is now an 
// async iterator instead of a promise:

(async () => {
  for await (const f of getFiles('.')) {
    console.log(f);
  }
})()

// I've written more about async iterators here: 
// https://qwtel.com/posts/software/async-generators-in-the-wild/

以上是关于javascript [node.js 8+]递归获取目录中的所有文件的主要内容,如果未能解决你的问题,请参考以下文章

Node.js资讯 | ES6 下的函数式:递归模式;JavaScript 深拷贝性能分析

8 行 Node.js 代码实现代理服务器

无法通过递归调用node.js中的函数从promises获得响应

在 node.js 中承诺一个递归函数

Node.js fs.readdir 递归目录搜索

Node.js fs.readdir 递归目录搜索