UNPKG

1.88 kBJavaScriptView Raw
1const fs = require('fs')
2const makePromise = require('makepromise')
3const read = require('./read')
4const { lstatFiles } = require('./lib/')
5
6/**
7 * Filter lstat results, taking only files if recursive is false.
8 * @param {lstat[]} files An array with lstat results
9 * @param {boolean} [recursive = false] Whether recursive mode is on
10 * @returns {lstat[]} Filtered array.
11 */
12function 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 * Read a directory, and return contents of contained files.
23 * @param {string} dirPath Path to the directory
24 * @param {boolean} [recursive=false] Whether to read found folders as well
25 * @returns {Promise<object>} An object reflecting directory structure, e.g.,
26 * { dir: subdir: { 'fileA.txt': 'foo', 'fileB.js': 'bar' }, 'fileC.jpg': 'baz' }
27 */
28async 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
55module.exports = readDir