-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtravel.js
48 lines (44 loc) · 1.03 KB
/
travel.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
const fs = require("fs");
const path = require("path");
/**
* 目录遍历 - 同步版
* @param {string} dir
* @param {func} callback
*/
function travelSync(dir, callback) {
fs.readdirSync(dir).forEach(function (file) {
var pathname = path.join(dir, file);
if (fs.statSync(pathname).isDirectory()) {
travel(pathname, callback);
} else {
callback(pathname);
}
});
}
/**
* 目录遍历 - 异步版
* @param {string} dir
* @param {func} callback
* @param {func} finish
*/
function travel(dir, callback, finish) {
fs.readdir(dir, function (err, files) {
(function next(i) {
if (i < files.length) {
let pathname = path.join(dir, files[i]);
fs.stat(pathname, function (err, stats) {
if (stats.isDirectory()) {
travel(pathname, callback, function () {
next(i + 1);
});
} else {
callback(pathname);
next(i + 1);
}
});
} else {
finish && finish();
}
})(0);
});
}