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

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

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-2021

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

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


posted @ 2024-09-05 13:30  xgqfrms  阅读(4)  评论(0编辑  收藏  举报