更改我的 nodejs 应用程序激活的方式

Change the way my nodejs app activates

下面列出的代码在 directory/subdirectories.

下搜索包含指定字符串的文件

要激活它,您输入 node [jsfilename] [folder] [ext] [term]

我想更改它以便它在没有基本文件夹的情况下进行搜索,我不想输入 ./ ,只是 node [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]);

如果我得到你想要达到的目标。您可以通过稍微更改最后一行中的函数调用来实现。

改变

searchFilesInDirectory(process.argv[2], process.argv[4], process.argv[3]);

searchFilesInDirectory(process.cwd(), process.argv[3], process.argv[2]);

编辑 正如@Keith 在评论中所说,使用 process.cwd() 获取当前工作目录而不是 __dirname

如果您希望它在两种情况下都有效,那么您需要进行条件检查...

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..");
}