-
Notifications
You must be signed in to change notification settings - Fork 0
/
4.3-recursive-find.js
77 lines (64 loc) · 2.23 KB
/
4.3-recursive-find.js
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import fs from 'fs'
import path from 'path'
const onError = err => console.error(err)
const checkKeywordInFile = (filePath, keyword, matchesCallback) => {
fs.readFile(filePath, 'utf-8', (fileReadErr, fileContent) => {
if (fileReadErr) {
return matchesCallback(fileReadErr)
}
if (!fileContent) {
return matchesCallback(null, false)
}
/* const resp = fileContent.split('\n').filter(line => line.includes(keyword))
if (!resp.length) {
return matchesCallback(null, false)
}
matchesCallback(null, true) */
return matchesCallback(null, fileContent.includes(keyword))
})
}
const findFileMatches = (dir, keyword, matches, cb) => {
fs.readdir(dir, { withFileTypes: true }, (readDirErr, files) => {
if (readDirErr) {
return cb(readDirErr)
}
let completed = 0
const { dirFiles, subDirs } = files.reduce((acc, curr) => {
acc[curr.isFile() ? 'dirFiles' : 'subDirs'].push(curr)
return acc
}, { dirFiles: [], subDirs: [] })
function iterate(index) {
if (index === subDirs.length) {
return cb(null, matches)
}
const newDirPath = path.join(dir, subDirs[index].name)
findFileMatches(newDirPath, keyword, matches, () => {
iterate(index + 1)
})
}
function doneCheck() {
// when finished searching for a match in the current files continue with the next directory
if (++completed === dirFiles.length) {
return iterate(0)
}
}
dirFiles.forEach(file => {
const filePath = path.join(dir, file.name)
checkKeywordInFile(filePath, keyword, (_, matching) => {
if (matching) {
matches.push(filePath)
}
doneCheck()
})
})
})
}
const recursiveFind = (dirPath, keyword, finalCallback) => {
findFileMatches(dirPath, keyword, [], (err, matches) => {
if (err) {
return onError(err)
}
finalCallback(matches)
})
}
recursiveFind('./filesToConcat', 'batman', console.log)