1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const fs = require('fs')
const path = require('path')
/**
* Calls a callback function on every file inside a directory.
* This is like fs.readdir(), but recurses on subdirectories.
*
* @param dir the name of the directory to search
* @param callback the function to call on each filename found
*/
const readdirRecursive = (dir, callback) =>
fs.readdir(dir, {withFileTypes: true}, (err, entries) => {
// If an error occurs, we currently just skip this directory.
// Ideally, we would report the error to the user...
if (err) return
for (const entry of entries) {
const entryPath = path.join(dir, entry.name)
if (entry.isDirectory()) readdirRecursive(entryPath, callback)
else callback(entryPath)
}
})
// Parse command-line arguments
let ignoreCase = false, recursive = false, invert = false, gunzip = false
let pattern
const files = []
for (const arg of process.argv.slice(2)) {
switch (arg) {
case '-i':
ignoreCase = true
break
case '-r':
recursive = true
break
case '-v':
invert = true
break
case '-z':
gunzip = true
break
default:
// The first non-flag argument is a pattern to search for.
// The rest are files (or directories, if -r is used).
if (pattern) files.push(arg)
else pattern = arg
}
}
if (!pattern) throw new Error('Syntax: node grep.js [-i] [-r] [-v] [-z] pattern ...files')
// TODO: implement grep