-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraverser.js
executable file
·47 lines (43 loc) · 1.24 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
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var path = require('path');
/**
* @param filePath the start path of traverse
* @param callback (err, res). res is the absolute path of file.
*/
function traverse(filePath, callback) {
filePath = path.resolve(filePath);
// get file stats
fs.lstat(filePath, function(err, stats) {
if (err) {
callback(err);
} else {
// check whether a file or dir
if (stats.isDirectory()) {
// get all files and dirs in directory
fs.readdir(filePath, function (err, files) {
if (err) {
callback(err);
} else {
files.forEach(function(item) {
// call traverse recursively
traverse(path.resolve(filePath, item), callback);
});
}
});
} else {
// return the file path.
callback(null, filePath);
}
}
});
}
/* call traverse */
traverse(process.argv[2], function(err, res) {
if (err) {
console.error(err);
} else {
console.log(res);
}
});