UNPKG

1.54 kBJavaScriptView Raw
1import * as fs from 'fs';
2import * as path from 'path';
3
4/**
5 * Recursively read the contents of a directory.
6 *
7 * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this
8 * directory.
9 * @returns Array holding all relative paths
10 */
11function deepReadDirSync(targetDir) {
12 var targetDirAbsPath = path.resolve(targetDir);
13
14 if (!fs.existsSync(targetDirAbsPath)) {
15 throw new Error(`Cannot read contents of ${targetDirAbsPath}. Directory does not exist.`);
16 }
17
18 if (!fs.statSync(targetDirAbsPath).isDirectory()) {
19 throw new Error(`Cannot read contents of ${targetDirAbsPath}, because it is not a directory.`);
20 }
21
22 // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it
23 // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve
24 // the difference between `targetDirAbsPath` and `currentDirAbsPath`.
25 var deepReadCurrentDir = (currentDirAbsPath) => {
26 return fs.readdirSync(currentDirAbsPath).reduce((absPaths, itemName) => {
27 var itemAbsPath = path.join(currentDirAbsPath, itemName);
28
29 if (fs.statSync(itemAbsPath).isDirectory()) {
30 return [...absPaths, ...deepReadCurrentDir(itemAbsPath)];
31 }
32
33 return [...absPaths, itemAbsPath];
34 }, []);
35 };
36
37 return deepReadCurrentDir(targetDirAbsPath).map(absPath => path.relative(targetDirAbsPath, absPath));
38}
39
40export { deepReadDirSync };
41//# sourceMappingURL=utils.js.map