-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdirectory-iterator.js
59 lines (48 loc) · 1.33 KB
/
directory-iterator.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
const fs = require("fs");
const promisifyReaddir = path => {
return new Promise((resolve, reject) => {
fs.readdir(path, (error, data) => {
if (error) {
reject(error);
} else {
resolve(data);
}
});
});
};
const promisifyStat = path => {
return new Promise((resolve, reject) => {
fs.lstat(path, (error, data) => {
if (error) {
reject(error);
} else {
resolve(data);
}
});
});
};
const filterDirectories = async paths => {
const stats = await Promise.all(
paths.map(async path => {
const stat = await promisifyStat(path);
const isDirectory = stat.isDirectory();
return isDirectory ? path : undefined;
})
);
return stats.filter(path => path !== undefined);
};
const iterateDirectoryAsync = async directoryPath => {
let paths = await promisifyReaddir(directoryPath);
paths = paths.map(path => `${directoryPath}/${path}`);
const directories = await filterDirectories(paths);
const files = paths.filter(path => directories.indexOf(path) === -1);
storedFiles = storedFiles.concat(files);
await Promise.all(
directories.map(directory => iterateDirectoryAsync(directory))
);
};
const basePath = "DIRECTORY START PATH";
let storedFiles = [];
iterateDirectoryAsync(basePath).then(() => {
console.log(storedFiles);
});