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

如何用Python Path.rglob匹配非node_modules目录下的所有package.json文件

解决方案

1. 用Shell的find命令(快速高效,适合终端/批量脚本)

直接利用find的-prune参数,在搜索阶段就跳过所有node_modules目录,无需遍历其中内容,性能最优:

find . -name "node_modules" -type d -prune -o -name "package.json" -type f -print
  • 逻辑说明:找到所有node_modules目录并标记为跳过(不深入遍历),同时匹配所有非node_modules目录下的package.json文件并输出路径。

2. Node.js递归遍历脚本(适合需要处理JSON内容的场景)

手动递归目录时,遇到node_modules直接跳过,不进入遍历:

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

async function collectPackageInfo(dir) {
  const entries = await fs.readdir(dir, { withFileTypes: true });
  const packageList = [];

  for (const entry of entries) {
    const fullPath = path.join(dir, entry.name);
    
    // 跳过node_modules目录,不继续遍历
    if (entry.isDirectory() && entry.name === 'node_modules') {
      continue;
    }

    if (entry.isDirectory()) {
      // 递归处理子目录
      const subPackages = await collectPackageInfo(fullPath);
      packageList.push(...subPackages);
    } else if (entry.isFile() && entry.name === 'package.json') {
      // 读取并解析package.json内容,可按需修改处理逻辑
      const content = await fs.readFile(fullPath, 'utf8');
      packageList.push({
        filePath: fullPath,
        data: JSON.parse(content)
      });
    }
  }
  return packageList;
}

// 从当前工作目录开始执行
collectPackageInfo(process.cwd())
  .then(result => console.log('收集到的package信息:', result))
  .catch(err => console.error('出错:', err));

3. Node.js glob库(简洁快速,适合批量获取文件路径)

借助glob库的忽略规则,在搜索阶段直接排除node_modules路径:
首先安装依赖:

npm install glob

然后编写脚本:

const glob = require('glob');

glob('**/package.json', {
  ignore: '**/node_modules/**', // 搜索阶段忽略所有node_modules下的内容
  absolute: true
}, (err, filePaths) => {
  if (err) throw err;
  // 后续可遍历filePaths读取每个package.json的内容
  console.log('找到的package.json路径:', filePaths);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 02:57:49