Node.js fast-glob报EACCES权限错误挂起,如何跳过无权限目录继续检索?
解决方案
fast-glob 配置修复
fast-glob 3.x版本同步模式下的suppressErrors参数存在未正确捕获EACCES权限错误的已知缺陷,会导致进程挂起,可通过以下两种方式修复:
- 方案1:切换到异步API,异步模式下错误处理逻辑更完善,不会出现挂起问题
import * as fg from 'fast-glob'; const globIncPaths = await fg(["/usr/lib/**"], { onlyDirectories: true, suppressErrors: true, throwErrorOnBrokenSymbolicLink: false });
- 方案2:自定义readdir方法预校验权限,适合必须使用同步API的场景
import * as fg from 'fast-glob'; import * as fs from 'fs'; const customReaddir = (path, options) => { try { fs.accessSync(path, fs.constants.R_OK); return fs.readdirSync(path, options); } catch (err) { if (err.code === 'EACCES' || err.code === 'EPERM') { return []; } throw err; } }; const globIncPaths = fg.sync(["/usr/lib/**"], { onlyDirectories: true, suppressErrors: true, fs: { readdir: customReaddir } });
替代方案推荐
Node.js 内置fs.glob(优先推荐)
Node.js 16.17+ 版本内置了glob实现,无额外依赖,性能表现优于fast-glob,原生支持跳过权限错误:
// 同步版本 import { globSync } from 'node:fs'; import * as fs from 'node:fs'; const globIncPaths = globSync('/usr/lib/**', { ignorePermissionErrors: true, nodir: false }).filter(p => fs.statSync(p).isDirectory()); // 异步版本(性能更佳) import { glob } from 'node:fs/promises'; const globIncPaths = (await glob('/usr/lib/**', { ignorePermissionErrors: true, nodir: false, withFileTypes: true })).filter(entry => entry.isDirectory()).map(entry => entry.fullpath());
经典glob包
npm上的成熟glob实现,生态兼容性好,配置简单即可跳过错误:
import { globSync } from 'glob'; const globIncPaths = globSync('/usr/lib/**', { strict: false, onlyDirectories: true });
内容的提问来源于stack exchange,提问作者gnikit
相关产品推荐
相关产品推荐

