Skip to content

Nodejs 获取指定文件夹下所有文件及文件夹

文件递归扁平化输出

代码

js
const fs = require('fs').promises;
const path = require('path');

// 递归获取文件夹下所有文件
async function flatFiles(dirPath) {
    try {
        const filesList = [];
        await readFile(dirPath, filesList);
        return filesList;
    } catch (error) {
        console.error('Error reading directory:', error);
        throw error;
    }
}

// 遍历读取文件
async function readFile(currentPath, filesList) {
    const files = await fs.readdir(currentPath);
    for (const file of files) {
        const filePath = path.join(currentPath, file);
        const stats = await fs.stat(filePath);
        if (stats.isDirectory()) {
            await readFile(filePath, filesList);
        } else {
            // 创建一个对象保存信息
            const obj = {};
            obj.size = stats.size; // 文件大小,以字节为单位
            obj.name = file; // 文件名
            obj.path = filePath; // 文件绝对路径
            filesList.push(obj);
        }
    }
}
const dirPath = 'E:/.temp/pdf/.idea';
(async () => {
    try {
        const list = await flatFiles(dirPath);
        console.log(JSON.stringify(list, null, 2));
    } catch (error) {
        console.error('Failed to get files and folders:', error);
    }
})();

用例结果

json
[
    {
        "size": 190,
        "name": ".gitignore",
        "path": "E:/.temp/pdf/.idea/.gitignore"
    },
    {
        "size": 0,
        "name": "1.txt",
        "path": "E:/.temp/pdf/.idea/a/1.txt"
    },
    {
        "size": 265,
        "name": "modules.xml",
        "path": "E:/.temp/pdf/.idea/modules.xml"
    },
    {
        "size": 330,
        "name": "pdf.iml",
        "path": "E:/.temp/pdf/.idea/pdf.iml"
    },
    {
        "size": 2912,
        "name": "workspace.xml",
        "path": "E:/.temp/pdf/.idea/workspace.xml"
    }
]

文件及文件夹以树状结构输出

代码

js
const fs = require('fs').promises;
const path = require('path');

// 获取文件夹下所有文件和子文件夹
async function treeFolderFiles(dirPath) {
    try {
        const items = await fs.readdir(dirPath);
        const result = [];

        for (const item of items) {
            const itemPath = path.join(dirPath, item);
            const stat = await fs.stat(itemPath);

            if (stat.isDirectory()) {
                let data = {
                    type: 'folder',
                    name: item,
                    children: []
                };
                let children = await treeFolderFiles(itemPath);
                if (children.length > 0) {
                    data.children = children;
                }
                result.push(data);
            } else {
                result.push({
                    type: 'file',
                    name: item,
                    path: itemPath,
                    size: stat.size
                });
            }
        }

        return result;
    } catch (error) {
        console.error(`Error reading directory ${dirPath}:`, error);
        throw error;
    }
}
const dirPath = 'E:/.temp/pdf/.idea';

(async () => {
    try {
        const list = await treeFolderFiles(dirPath);
        console.log(JSON.stringify(list, null, 2));
    } catch (error) {
        console.error('Failed to get files and folders:', error);
    }
})();

用例结果

json
[
  {
    "type": "file",
    "name": ".gitignore",
    "path": "E:/.temp/pdf/.idea/.gitignore",
    "size": 190
  },
  {
    "type": "folder",
    "name": "a",
    "children": [
      {
        "type": "file",
        "name": "1.txt",
        "path": "E:/.temp/pdf/.idea/a/1.txt",
        "size": 0
      }
    ]
  },
  {
    "type": "file",
    "name": "modules.xml",
    "path": "E:/.temp/pdf/.idea/modules.xml",
    "size": 265
  },
  {
    "type": "file",
    "name": "pdf.iml",
    "path": "E:/.temp/pdf/.idea/pdf.iml",
    "size": 330
  },
  {
    "type": "file",
    "name": "workspace.xml",
    "path": "E:/.temp/pdf/.idea/workspace.xml",
    "size": 2912
  }
]
/src/technology/dateblog/2025/05/20250507-nodejs-%E8%8E%B7%E5%8F%96%E6%8C%87%E5%AE%9A%E6%96%87%E4%BB%B6%E5%A4%B9%E4%B8%8B%E6%89%80%E6%9C%89%E6%96%87%E4%BB%B6%E5%8F%8A%E6%96%87%E4%BB%B6%E5%A4%B9.html