packagejson 实现 find 命令
首先,需要使用 Node.js 的文件系统模块 fs 来读取当前目录下的所有文件和子目录。然后,使用递归方式遍历整个目录树,查找包含指定关键字的文件。
在 package.json 中添加以下内容:
{
"name": "find",
"version": "1.0.0",
"description": "Find files with a given keyword",
"bin": {
"find": "./find.js"
},
"author": "Your Name",
"license": "MIT"
}
在同级目录下创建 find.js 文件,使用以下代码实现 find 命令:
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const keyword = process.argv[2];
if (!keyword) {
console.log('Usage: find <keyword>');
process.exit(1);
}
function findFiles(dir) {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
findFiles(filePath);
} else if (file.includes(keyword)) {
console.log(filePath);
}
}
}
findFiles('.');
运行 npm link 命令将 find 命令添加到全局环境中。然后,在终端中输入 find <keyword> 命令即可查找包含指定关键字的文件
原文地址: http://www.cveoy.top/t/topic/g7ki 著作权归作者所有。请勿转载和采集!