-
Notifications
You must be signed in to change notification settings - Fork 0
/
traverser.js
58 lines (52 loc) · 1.66 KB
/
traverser.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
'use strict';
var fs = require('fs');
var path = require('path');
var Promise = require('bluebird');
var fslstat = Promise.promisify(fs.lstat);
var fsreaddir = Promise.promisify(fs.readdir);
// function traverse(rootPath)
function traverse(list, fileList) {
return new Promise(function (resolve) {
if (typeof list === 'string') {
list = [ list ];
}
fileList = fileList || [];
// dequeue a item
var current = list.shift();
if (current) {
resolve(task(current, list, fileList));
} else {
// no more path in target list, resolve final result
resolve(fileList);
}
})
}
function task (current, list, fileList) {
return fslstat(current)
.then(function (stats) {
if (stats.isDirectory()){
// if current path is subdir, list this subdir
return fsreaddir(current)
.then(function(files) {
var paths = files.map(function (item) {
return path.resolve(current, item);
});
list = list.concat(paths);
return traverse(list, fileList);
});
} else {
// add file path to result list.
fileList.push(current);
return traverse(list, fileList);
}
});
}
/* call traverse */
/* promise api */
traverse(process.argv[2])
.then(function(res) {
console.log(res.length + '\n' + JSON.stringify(res));
})
.catch(function(err) {
console.error('Catch Error:', err);
});