How to use Node.js to get all files full paths that nested in folders All In One

xgqfrms / 2024-09-06 / 原文

How to use Node.js to get all files full paths that nested in folders All In One

如何使用 Node.js 获取文件夹中嵌套的所有文件的完整路径

image

demos

ESM

// ❌
// import fs from 'node:fs/promises';
// ✅
// import * as fs from 'node:fs/promises';

import { readdir } from 'node:fs/promises';
import * as fs from 'node:fs';

import * as path from  'node:path';

async function main() {
  async function findFiles(folderName, arr = []) {
    let result = arr || [];
    // const items = await fs.readdir(folderName, { withFileTypes: true });
    const items = await readdir(folderName, { withFileTypes: true });
    // ✅ fix
    for (const item of items) {
      const name = path.join(folderName, item.name);
      if (path.extname(item.name) === ".json") {
        // file
        console.log(`Found file: ${item.name} in folder: ${folderName}`);
        result.push(name);
      } else {
        // console.log(`fs.stat`, fs.stat)
        fs.stat(name, async (err, stats) => {
          console.log(`name =`, name)
          // console.log(`stats =`, stats)
          // is a folder
          if(stats.isDirectory()) {
            await findFiles(name, result);
          } else {
            // ignore
          }
        })
      }
    }
    return result;
  }
  const files = await findFiles("stores");
  console.log(`❓files =`, files);
}

main();

/*

 $ node ./fs-get-files-full-path.js
Found file: data.json in folder: stores
❓files = [ 'stores/data.json' ]
name = stores/101
name = stores/201
name = stores/2022
name = stores/2024
name = stores/readme.md
Found file: data.json in folder: stores/101
Found file: data.json in folder: stores/201
name = stores/2022/11
name = stores/2024/09
name = stores/2022/11/11
name = stores/2024/09/01
Found file: data.json in folder: stores/2022/11/11
Found file: data.json in folder: stores/2024/09/01


*/

CJS

const fs = require("fs").promises;
const path = require("path");

async function main() {
  async function findFiles(folderName, arr = []) {
    let result = arr || [];
    const items = await fs.readdir(folderName, { withFileTypes: true });
    // ✅ fix
    for (const item of items) {
      const name = path.join(folderName, item.name);
      if (path.extname(item.name) === ".json") {
        // file
        console.log(`Found file: ${item.name} in folder: ${folderName}`);
        result.push(name);
      } else {
        // folder
        await findFiles(name, result);
      }
    }
    return result;
  }
  const files = await findFiles("stores");
  console.log(`❓files =`, files);
}

main();

/*

$ node ./bug-fix.cjs

Found file: sales.json in folder: stores/201
Found file: sales.json in folder: stores/202
Found file: data.json in folder: stores/2022/11/11
❓files = [
  'stores/201/sales.json',
  'stores/202/sales.json',
  'stores/2022/11/11/data.json',
]

*/

https://gitlab.com/webgeeker/node.js-file-system/-/blob/main/bug-fix.js?ref_type=heads

https://gitlab.com/webgeeker/node.js-file-system/-/tree/main?ref_type=heads

refs

https://nodejs.org/api/fs.html

How to use Node.js to expand all nested folders and files in the file tree to generate a layer of full file paths All In One



©xgqfrms 2012-2021

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!