-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscanDirEach.js
71 lines (60 loc) · 1.59 KB
/
scanDirEach.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
import { readdirSync } from "fs";
import { join } from "path";
import eachOf from "async/eachOf.js";
export default function scanDirEach(path, worker = () => true, raw = false) {
return new Promise((resolve, reject) => {
const WORKPIECES = [];
const FILES = readdirSync(path, { withFileTypes: true });
let changed = false;
function switcher({ wp, pivot }) {
switch (Object.prototype.toString.call(wp)) {
case "[object Object]":
WORKPIECES.push(wp);
if (!Object.is(wp, pivot) && !changed) changed = true;
break;
case "[object Boolean]":
if (wp) {
WORKPIECES.push(pivot);
break;
}
changed = true;
break;
default:
WORKPIECES.push(pivot);
break;
}
}
eachOf(
FILES,
(dirent, index, cb) => {
let pivot = {
path: join(path, dirent.name),
dirent,
};
if (raw) FILES[index] = pivot;
const MAPPED = worker(pivot, index, FILES);
if (Object.prototype.toString.call(MAPPED) === "[object Promise]") {
MAPPED.then(
(tv) => {
switcher({ wp: tv, pivot });
cb(null);
},
(err) => {
cb(err);
}
);
return;
}
switcher({ wp: MAPPED, pivot });
cb(null);
},
(err) => {
if (!err) {
resolve(raw ? [WORKPIECES, changed ? FILES : false] : WORKPIECES);
return;
}
reject(err);
}
);
});
}