下面列出的代码会搜索在其目录/子目录下包含指定字符串的文件。
要激活它,键入node [jsfilename] [folder] [ext] [term]
我想更改它以便它将在没有基本文件夹的情况下进行搜索,我不想输入./
,只需要节点[jsfilename] [ext] [term]
所以它已经知道从它的位置搜索。
我知道它与process.argv
有关但需要提示我该怎么做。
PS :. 我已经尝试将最后一个原始文件更改为: searchFilesInDirectory(__ dirname,process.argv [3],process.argv [2]); 它让我注意到......
const path = require('path');
const fs = require('fs');
function searchFilesInDirectory(dir, filter, ext) {
if (!fs.existsSync(dir)) {
console.log(`Welcome! to start, type node search [location] [ext] [word]`);
console.log(`For example: node search ./ .txt myterm`);
return;
}
const files = fs.readdirSync(dir);
const found = getFilesInDirectory(dir, ext);
let printed = false
found.forEach(file => {
const fileContent = fs.readFileSync(file);
const regex = new RegExp('\\b' + filter + '\\b');
if (regex.test(fileContent)) {
console.log(`Your word has found in file: ${file}`);
}
if (!printed && !regex.test(fileContent)) {
console.log(`Sorry, Noting found`);
printed = true;
}
});
}
function getFilesInDirectory(dir, ext) {
if (!fs.existsSync(dir)) {
console.log(`Specified directory: ${dir} does not exist`);
return;
}
let files = [];
fs.readdirSync(dir).forEach(file => {
const filePath = path.join(dir, file);
const stat = fs.lstatSync(filePath);
if (stat.isDirectory()) {
const nestedFiles = getFilesInDirectory(filePath, ext);
files = files.concat(nestedFiles);
} else {
if (path.extname(file) === ext) {
files.push(filePath);
}
}
});
return files;
}
searchFilesInDirectory(process.argv[2], process.argv[4], process.argv[3]);
答案 0 :(得分:1)
如果我得到你想要实现的目标。您可以通过在最后一行稍微更改函数调用来完成此操作。
更改
searchFilesInDirectory(process.argv[2], process.argv[4], process.argv[3]);
到
searchFilesInDirectory(process.cwd(), process.argv[3], process.argv[2]);
修改强>
正如@Keith在评论中所说,使用process.cwd()
获取当前工作目录而不是__dirname
答案 1 :(得分:1)
如果您希望它适用于这两种情况,那么您需要进行条件检查...
if(process.argv.length === 5){
searchFilesInDirectory(process.argv[2], process.argv[4], process.argv[3]);
}else if(process.argv.length === 4){
searchFilesInDirectory(process.cwd(), process.argv[3], process.argv[2]);
}else{
throw new Error("Not enough arguments provided..");
}