-
Notifications
You must be signed in to change notification settings - Fork 39
/
walker.js
77 lines (64 loc) · 3.02 KB
/
walker.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
'use strict';
const fs = require('fs'),
Emitter = require('events').EventEmitter,
emitter = new Emitter(),
eventState = require('event-state'),
dirTree = (path, cb) => {
const buildBranch = (path, branch) => {
fs.readdir(path, (err, files) => {
if (err) {
//Errors result in a false value in the tree.
branch[path] = false;
cb(err);
} else {
const newEvents = files.map(file => {
return path + '/' + file;
});
if (!state) {
// If this is the first iteration,
// initialize the dynamic state machine (DSM).
state = emitter.required(newEvents, () => {
// Allow for multiple paradigms vis-a-vis callback and promises.
// resolve the promise with the completed tree..
cb(null, tree);
});
} else {
// Add events to the DSM for the directory's children
state.add(newEvents);
}
// Check each file descriptor to see if it's a directory.
files.forEach(file => {
const filePath = path + '/' + file;
fs.stat(filePath, (err, stats) => {
if (err) {
// Errors result in a false value in the tree
branch[file] = false;
emitter.emit(filePath, true);
} else if (stats.isDirectory() && file[0] !== '.' && file !== 'node_modules') {
// Directories are object properties on the tree.
branch[file] = {};
//console.log('cur dir name', file);
// Recurse into the directory.
buildBranch(filePath, branch[file]);
} else {
const fp = filePath.replace(process.cwd(), '');
//console.log(dir, file);
// If it's not a directory, it's a file.
// Files get a true value in the tree.
branch[file] = fp;
emitter.emit(filePath, true);
}
});
});
}
//Once we've read the directory, we can raise the event for the parent
// directory and let it's children take care of themselves.
emitter.emit(path, true);
});
};
let tree = {},
state;
return buildBranch(path, tree);
};
emitter.required = eventState;
module.exports = dirTree;