Skip to content

Instantly share code, notes, and snippets.

@tvvignesh tvvignesh/program.js
Created Mar 19, 2018

Embed
What would you like to do?
Grep implementation in Node.js
/*
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);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.