Skip to content

Commit 1bb540c

Browse files
authored
added directory iterator
the above script iterates through all the directories recursively and list the files
1 parent 2f18043 commit 1bb540c

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

directory-iterator.js

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
const fs = require("fs");
2+
3+
const promisifyReaddir = path => {
4+
return new Promise((resolve, reject) => {
5+
fs.readdir(path, (error, data) => {
6+
if (error) {
7+
reject(error);
8+
} else {
9+
resolve(data);
10+
}
11+
});
12+
});
13+
};
14+
15+
const promisifyStat = path => {
16+
return new Promise((resolve, reject) => {
17+
fs.lstat(path, (error, data) => {
18+
if (error) {
19+
reject(error);
20+
} else {
21+
resolve(data);
22+
}
23+
});
24+
});
25+
};
26+
27+
const filterDirectories = async paths => {
28+
const stats = await Promise.all(
29+
paths.map(async path => {
30+
const stat = await promisifyStat(path);
31+
const isDirectory = stat.isDirectory();
32+
return isDirectory ? path : undefined;
33+
})
34+
);
35+
return stats.filter(path => path !== undefined);
36+
};
37+
38+
const iterateDirectoryAsync = async directoryPath => {
39+
let paths = await promisifyReaddir(directoryPath);
40+
41+
paths = paths.map(path => `${directoryPath}/${path}`);
42+
43+
const directories = await filterDirectories(paths);
44+
45+
const files = paths.filter(path => directories.indexOf(path) === -1);
46+
47+
storedFiles = storedFiles.concat(files);
48+
49+
await Promise.all(
50+
directories.map(directory => iterateDirectoryAsync(directory))
51+
);
52+
};
53+
54+
const basePath = "DIRECTORY START PATH";
55+
let storedFiles = [];
56+
57+
iterateDirectoryAsync(basePath).then(() => {
58+
console.log(storedFiles);
59+
});

0 commit comments

Comments
 (0)