-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrwalk.js
More file actions
100 lines (80 loc) · 2.14 KB
/
rwalk.js
File metadata and controls
100 lines (80 loc) · 2.14 KB
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
97
98
99
100
/*jshint strict:true node:true es5:true onevar:true laxcomma:true laxbreak:true eqeqeq:true immed:true latedef:true*/
(function () {
"use strict";
var fs = require('fs')
, path = require('path')
, EventEmitter = require('events').EventEmitter
;
fs.exists = fs.exists || path.exists;
// TODO make into a real emitter subclass
function readstats(cb, pathname, nodes, stats) {
var node = nodes.pop()
;
fs.lstat(path.join(pathname, node), function (err, stat) {
stat = stat || { error: err };
stat.path = pathname;
stat.name = node;
stats.push(stat);
if (nodes.length > 0) {
readstats(cb, pathname, nodes, stats);
} else {
cb(null, stats);
}
});
}
function readdir(cb, dir) {
fs.readdir(dir, function (err, nodes) {
if (err) {
cb(err);
return;
}
readstats(cb, dir, nodes, []);
});
}
function rwalk(emitter, fullpath) {
readdir(function (err, stats) {
function next() {
var fullpathArr
;
// TODO handle escaped pathnames i.e. /path/to\/thing/here
if ('/' === fullpath) {
emitter.emit('end');
return;
}
fullpathArr = fullpath.split(path.sep);
fullpathArr.pop();
fullpath = fullpathArr.join(path.sep) || '/';
rwalk(emitter, fullpath);
}
emitter.emit('nodes', next, err, fullpath, stats);
}, fullpath);
}
function rwalkHelper(fullpath) {
var emitter = new EventEmitter()
;
fullpath = path.normalize(path.resolve(process.cwd(), fullpath));
rwalk(emitter, fullpath);
return emitter;
}
function run() {
var emitter = rwalkHelper(process.argv[2])
;
emitter.on('nodes', function (next, err, dir, stats) {
if (err) {
console.error(err);
console.error('couldn\'t find ' + process.argv[2]);
next();
return;
}
console.log(dir, stats.length);
next();
});
emitter.on('end', function () {
console.log('all done');
});
}
if (require.main === module) {
run();
}
exports.rwalk = rwalkHelper;
}());