Created
October 17, 2016 18:33
-
-
Save shovon/38ed7e3fbc504494cf696678f60a9c26 to your computer and use it in GitHub Desktop.
Grep in Node.js
This file contains hidden or 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
| 'use strict'; | |
| const fs = require('fs'); | |
| const readline = require('readline'); | |
| const flags = { | |
| n: 'Show line number' | |
| }; | |
| const printHelp = () => { | |
| console.log('ngrep [options] [pattern] [file]'); | |
| console.log(''); | |
| console.log('Options'); | |
| Object.keys(flags).forEach(key => { | |
| console.log('\t', `-${key}`, '\t', flags[key]); | |
| }); | |
| }; | |
| const printHelpAndExitWithError = (message) => { | |
| console.error(message); | |
| console.error(''); | |
| printHelp(); | |
| process.exit(1); | |
| } | |
| const commandArguments = process.argv.slice(2); | |
| let options = commandArguments.slice(0, -2); | |
| let pattern = commandArguments[commandArguments.length - 2]; | |
| const filename = commandArguments[commandArguments.length - 1]; | |
| if (!process.stdin.isTTY) { | |
| options = commandArguments.slice(2, 1); | |
| pattern = commandArguments[commandArguments.length - 1]; | |
| } else { | |
| if (typeof pattern !== 'string') { | |
| printHelpAndExitWithError('Pattern expected'); | |
| } else if (typeof filename !== 'string') { | |
| printHelpAndExitWithError('Filename expected'); | |
| } | |
| } | |
| if (typeof pattern !== 'string') { | |
| printHelpAndExitWithError('Pattern expected') | |
| } | |
| const setFlags = { | |
| }; | |
| options.forEach((arg) => { | |
| if (!/^-\w$/.test(arg)) { | |
| printHelpAndExitWithError(`Bad argument '${arg}'`); | |
| } | |
| const flag = arg.slice(-1); | |
| if (!flags[flag]) { | |
| printHelpAndExitWithError('Bad argument'); | |
| } | |
| setFlags[flag] = true; | |
| }); | |
| const regex = new RegExp(pattern); | |
| let lineNumber = 1; | |
| let found = false; | |
| let instream = process.stdin; | |
| if (process.stdin.isTTY) { | |
| instream = fs.createReadStream(filename); | |
| } | |
| const rl = readline.createInterface({ input: instream }); | |
| rl.on('line', (input) => { | |
| if (regex.test(input)) { | |
| found = true; | |
| if (setFlags.n) { | |
| console.log(`${lineNumber}:${input}`); | |
| } else { | |
| console.log(input); | |
| } | |
| } | |
| lineNumber++; | |
| }); | |
| process.on('beforeExit', () => { | |
| if (!found) { | |
| process.exit(1); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment