-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4.2-list-nested-files.js
46 lines (36 loc) · 1.19 KB
/
4.2-list-nested-files.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
import fs from 'fs'
import path from 'path'
const onError = err => console.error(err)
const readDir = (currentFilePath, allFiles, done) => {
fs.readdir(currentFilePath, { withFileTypes: true }, (err, files) => {
if (err) {
return done(err)
}
const { realFiles, realDirs } = files.reduce((acc, curr) => {
acc[curr.isFile() ? 'realFiles' : 'realDirs'].push(curr)
return acc
}, { realFiles: allFiles, realDirs: [] })
function iterate(index) {
if (index == realDirs.length) {
return process.nextTick(() => {
done(null, realFiles.map(f => f.name))
})
}
const newDir = realDirs[index]
const newDirPath = path.join(currentFilePath, newDir.name)
readDir(newDirPath, realFiles, () => {
iterate(index + 1)
})
}
iterate(0)
})
}
const listNestedFile = (dirPath, finalCallback) => {
readDir(dirPath, [], (err, allFiles) => {
if (err) {
return onError(err)
}
finalCallback(allFiles)
})
}
listNestedFile('./filesToConcat', console.log)