Created
March 19, 2018 18:01
-
-
Save tvvignesh/4140618dbfc545930af892796059f6ec to your computer and use it in GitHub Desktop.
Grep implementation in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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