如何用Node.js原生API替代有高危漏洞的shelljs实现文件遍历?
用Node.js原生API替代shelljs实现文件遍历
你找错模块了——文件系统相关操作属于fs模块的范畴,os模块是用来获取操作系统相关信息(比如内存、CPU架构)的,和文件遍历无关。
下面是两种原生实现方式,完全匹配你原来的需求:遍历当前目录下所有.c文件,同时排除路径中包含DDD的文件。
同步实现(和shelljs逻辑最接近,同步阻塞)
这种方式和你原来的shelljs代码执行逻辑一致,适合简单脚本场景:
const fs = require('fs'); const path = require('path'); function findFiles(dir) { let results = []; // 读取目录内容,同时获取文件类型 const items = fs.readdirSync(dir, { withFileTypes: true }); for (const item of items) { const fullPath = path.join(dir, item.name); // 跳过包含DDD的路径 if (fullPath.includes('DDD')) continue; if (item.isDirectory()) { // 递归遍历子目录 results = results.concat(findFiles(fullPath)); } else { // 筛选.c后缀的文件 if (item.name.endsWith('.c')) { results.push(fullPath); } } } return results; } const files = findFiles('.'); console.log(files);
异步实现(非阻塞,推荐生产环境使用)
如果是在服务端等需要避免阻塞事件循环的场景,推荐用异步版本:
const fs = require('fs').promises; const path = require('path'); async function findFiles(dir) { let results = []; const items = await fs.readdir(dir, { withFileTypes: true }); for (const item of items) { const fullPath = path.join(dir, item.name); if (fullPath.includes('DDD')) continue; if (item.isDirectory()) { results = results.concat(await findFiles(fullPath)); } else { if (item.name.endsWith('.c')) { results.push(fullPath); } } } return results; } // 调用异步函数并处理结果 findFiles('.') .then(files => console.log(files)) .catch(err => console.error('遍历出错:', err));
运行效果
两种实现的输出都和你原来的shelljs代码一致:
[ 'AAA/main.c', 'BBB/go.c', 'BBB/run.c' ]
核心逻辑说明
fs.readdirSync/fs.promises.readdir:读取目录内容,开启withFileTypes: true可以直接拿到文件类型,避免额外调用fs.stat判断文件/目录path.join:自动处理跨平台路径分隔符,避免手动拼接路径出现的兼容性问题- 递归遍历子目录时直接跳过包含
DDD的路径,最后筛选出.c后缀的文件
内容的提问来源于stack exchange,提问作者OrenIshShalom
相关产品推荐
相关产品推荐

