Skip to content

Commit e0da8e0

Browse files
add args handling to basic-grep.js cli
1 parent b590c2a commit e0da8e0

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

Languages/JavaScript/nodejs/basic-grep.js

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,32 @@
1-
// Program to filter lines of a file that include a word and paint the match. Like basic grep command.
2-
// TODO add cli input
1+
/**
2+
Program to search a word in a file, like basic grep.
3+
For example, `node basic-grep.js history.txt docker`,
4+
will search the word `docker` inside the history.txt file.
5+
**/
36

47
import { readFile } from "node:fs/promises";
58
import chalk from "chalk";
69

710
const main = async () => {
811
let text;
12+
const [file, word] = getArgs();
13+
if (!file || !word) {
14+
throw new Error("need to supply file and search word");
15+
process.exit(1);
16+
}
917
try {
10-
text = await readFile("history.txt", "utf-8");
18+
text = await readFile(file, "utf-8");
1119
} catch (error) {
1220
if (error.code === "ENOENT") {
1321
console.log("Not such file in path");
14-
return
22+
process.exit(1);
1523
} else {
1624
throw error;
1725
}
1826
}
1927
const history = text.split("\n");
2028

21-
searchWord(history, "node");
29+
searchWord(history, word);
2230
};
2331

2432
const searchWord = (arr, word) => {
@@ -45,10 +53,10 @@ const paintWord = (text, searchWord) => {
4553
console.log(word);
4654
};
4755

48-
const getWordIndexes = (indices, len) => {
56+
const getWordIndexes = (indexes, len) => {
4957
const result = [];
5058

51-
indices.forEach((index) => {
59+
indexes.forEach((index) => {
5260
for (let i = 0; i < len; i++) {
5361
result.push(index + i);
5462
}
@@ -57,4 +65,10 @@ const getWordIndexes = (indices, len) => {
5765
return result;
5866
};
5967

68+
const getArgs = () => {
69+
const args = process.argv.splice(2);
70+
71+
return args;
72+
};
73+
6074
main();

0 commit comments

Comments
 (0)