javascript Node.js中的Grep实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Node.js中的Grep实现相关的知识,希望对你有一定的参考价值。

/*
Instructions to run:
node program.js grep "search term" file1.xyz file2.xyz /path/to/file/file3.xyz
*/

var fileList = [];
var countObj = {};

console.log(process.argv);

if(process.argv[2]=="grep"){

  process.argv[3] = process.argv[3].replace(/"/g,"");

    for(var i=4;i<process.argv.length;i++){
        fileList.push(process.argv[i]);

        let readline = require('readline');
        let fs = require('fs');

        let rl = readline.createInterface({
          input: fs.createReadStream(process.argv[i]),
          crlfDelay: Infinity
        });

        rl.on('line', (line) => {
          console.log(`\n\nLine from file: ${line}`);

            let re = new RegExp(process.argv[3], 'g');
            let arrList = line.match(re);

            if(!countObj[rl.input.path])countObj[rl.input.path]=0;
            countObj[rl.input.path]++;
            if(!arrList)return;
                for(var j=0;j<arrList.length;j++){
                if(process.argv[3]==arrList[j])console.log('\n\nelement found at line '+countObj[rl.input.path]+' in file '+rl.input.path);
            }
        });
    }
}

以上是关于javascript Node.js中的Grep实现的主要内容,如果未能解决你的问题,请参考以下文章