You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何用fs.readdirSync处理带通配符的动态目录路径?

能否用带通配符的路径调用fs.readdirSync获取多层子目录?

Node.js 原生的fs.readdirSync不支持直接解析带通配符(如*)的路径,它仅接受具体的目录路径作为参数,无法自动匹配多层级的目录结构。

以下是两种更高效的替代方案,比嵌套循环更易维护:

方案1:使用第三方glob包(推荐)

glob是Node.js生态中专门处理文件路径通配符的工具包,能轻松解析./src/images/*/*/*这类模式,还支持只筛选目录。

步骤:

  • 安装依赖:
    npm install glob
    
  • 示例代码:
    const glob = require('glob');
    
    // 匹配src/images下第三层的所有子目录
    const targetDirectories = glob.sync('./src/images/*/*/*', {
      onlyDirectories: true, // 只返回目录,排除文件
      absolute: false // 可选,设为true返回绝对路径
    });
    
    console.log(targetDirectories);
    

方案2:自定义递归遍历(无额外依赖)

如果不想引入第三方包,可以写一个递归函数来遍历目录,收集符合层级要求的子目录:

const fs = require('fs');
const path = require('path');

function getTargetDirectories(basePath, targetDepth, currentDepth = 0) {
  let directories = [];
  const items = fs.readdirSync(basePath, { withFileTypes: true });

  for (const item of items) {
    const fullPath = path.join(basePath, item.name);
    if (item.isDirectory()) {
      if (currentDepth + 1 === targetDepth) {
        // 达到目标层级,加入结果
        directories.push(fullPath);
      } else {
        // 未达到目标层级,继续递归
        directories = directories.concat(
          getTargetDirectories(fullPath, targetDepth, currentDepth + 1)
        );
      }
    }
  }
  return directories;
}

// 调用:获取src/images下第3层的子目录(basePath为第0层)
const result = getTargetDirectories('./src/images', 3);
console.log(result);

两种方案各有优劣:glob包成熟稳定,能处理各种复杂通配符场景;自定义递归则更灵活,适合需要特殊逻辑的场景。

内容的提问来源于stack exchange,提问作者Joseph Walsh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 12:31:23