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
+ **/
3
6
4
7
import { readFile } from "node:fs/promises" ;
5
8
import chalk from "chalk" ;
6
9
7
10
const main = async ( ) => {
8
11
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
+ }
9
17
try {
10
- text = await readFile ( "history.txt" , "utf-8" ) ;
18
+ text = await readFile ( file , "utf-8" ) ;
11
19
} catch ( error ) {
12
20
if ( error . code === "ENOENT" ) {
13
21
console . log ( "Not such file in path" ) ;
14
- return
22
+ process . exit ( 1 ) ;
15
23
} else {
16
24
throw error ;
17
25
}
18
26
}
19
27
const history = text . split ( "\n" ) ;
20
28
21
- searchWord ( history , "node" ) ;
29
+ searchWord ( history , word ) ;
22
30
} ;
23
31
24
32
const searchWord = ( arr , word ) => {
@@ -45,10 +53,10 @@ const paintWord = (text, searchWord) => {
45
53
console . log ( word ) ;
46
54
} ;
47
55
48
- const getWordIndexes = ( indices , len ) => {
56
+ const getWordIndexes = ( indexes , len ) => {
49
57
const result = [ ] ;
50
58
51
- indices . forEach ( ( index ) => {
59
+ indexes . forEach ( ( index ) => {
52
60
for ( let i = 0 ; i < len ; i ++ ) {
53
61
result . push ( index + i ) ;
54
62
}
@@ -57,4 +65,10 @@ const getWordIndexes = (indices, len) => {
57
65
return result ;
58
66
} ;
59
67
68
+ const getArgs = ( ) => {
69
+ const args = process . argv . splice ( 2 ) ;
70
+
71
+ return args ;
72
+ } ;
73
+
60
74
main ( ) ;
0 commit comments