xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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

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

https://www.cnblogs.com/xgqfrms/p/18370588



©xgqfrms 2012-2025

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

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


posted @   xgqfrms  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2023-09-05 如何编写出简洁高效的 prompt 来释放出 ChatGPT 更加强大的能力 All In One
2023-09-05 CSS filter drop-shadow All In One
2023-09-05 How to fix waitForFunction TimeoutError of puppeteer All In One
2022-09-05 Rust Cargo All In One
2022-09-05 WebAssembly get_local error All In One
2022-09-05 Rust & WebAssembly All In One
2022-09-05 WebAssembly Explorer All In One
点击右上角即可分享
微信分享提示