1 | const fs = require('fs')
|
2 | const makePromise = require('makepromise')
|
3 | const read = require('./read')
|
4 | const { lstatFiles } = require('./lib/')
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | function filterFiles(files, recursive) {
|
13 | const fileOrDir = (lstat) => {
|
14 | return lstat.isFile() || lstat.isDirectory()
|
15 | }
|
16 | return files.filter(({ lstat }) => {
|
17 | return recursive ? fileOrDir(lstat) : lstat.isFile()
|
18 | })
|
19 | }
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 | async function readDir(dirPath, recursive = false) {
|
29 | const contents = await makePromise(fs.readdir, [dirPath])
|
30 | const lstatRes = await lstatFiles(dirPath, contents)
|
31 | const filteredFiles = filterFiles(lstatRes, recursive)
|
32 |
|
33 | const promises = filteredFiles.map(async ({ lstat, path, relativePath }) => {
|
34 | let promise = Promise.resolve()
|
35 | if (lstat.isDirectory()) {
|
36 | promise = readDir(path, recursive)
|
37 | } else if (lstat.isFile()) {
|
38 | promise = read(path)
|
39 | }
|
40 | const data = await promise
|
41 | return { relativePath, data }
|
42 | })
|
43 | const allRead = await Promise.all(promises)
|
44 | const res = allRead.reduce(
|
45 | (acc, { data, relativePath }) => {
|
46 | const d = {
|
47 | [relativePath]: data,
|
48 | }
|
49 | return Object.assign(acc, d)
|
50 | }, {}
|
51 | )
|
52 | return res
|
53 | }
|
54 |
|
55 | module.exports = readDir
|