forked from jergason/recursive-readdir
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (83 loc) · 2.09 KB
/
index.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
var fs = require("fs");
var p = require("path");
var minimatch = require("minimatch");
function patternMatcher(pattern) {
return function(path, stats) {
var minimatcher = new minimatch.Minimatch(pattern, { matchBase: true });
return (!minimatcher.negate || stats.isFile()) && minimatcher.match(path);
};
}
function toMatcherFunction(ignoreEntry) {
if (typeof ignoreEntry == "function") {
return ignoreEntry;
} else {
return patternMatcher(ignoreEntry);
}
}
function readdir(path, ignores, callback) {
if (typeof ignores == "function") {
callback = ignores;
ignores = [];
}
if (!callback) {
return new Promise(function(resolve, reject) {
readdir(path, ignores || [], function(err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
ignores = ignores.map(toMatcherFunction);
var list = [];
fs.readdir(path, function(err, files) {
if (err) {
return callback(err);
}
var pending = files.length;
if (!pending) {
// we are done, woop woop
return callback(null, list);
}
files.forEach(function(file) {
var filePath = p.join(path, file);
fs.stat(filePath, function(_err, stats) {
if (_err) {
return callback(_err);
}
if (
ignores.some(function(matcher) {
return matcher(filePath, stats);
})
) {
pending -= 1;
if (!pending) {
return callback(null, list);
}
return null;
}
if (stats.isDirectory()) {
readdir(filePath, ignores, function(__err, res) {
if (__err) {
return callback(__err);
}
list = list.concat(res);
pending -= 1;
if (!pending) {
return callback(null, list);
}
});
} else {
list.push(filePath);
pending -= 1;
if (!pending) {
return callback(null, list);
}
}
});
});
});
}
module.exports = readdir;