-
Notifications
You must be signed in to change notification settings - Fork 11
/
dive.js
109 lines (94 loc) · 2.74 KB
/
dive.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
97
98
99
100
101
102
103
104
105
106
107
108
109
var fs = require('fs');
var path = require('path');
// default options
var defaultOpt = {
all: false,
recursive: true,
files: true,
directories: false,
ignore: false
};
function defaults(defaults, obj) {
for (var prop in defaults)
if (defaults.hasOwnProperty(prop))
if (!obj.hasOwnProperty(prop))
obj[prop] = defaults[prop];
return obj;
}
// general function
module.exports = function(dir, opt, action, complete) {
// check args
if (typeof opt === 'function') {
if (typeof action === 'undefined')
complete = function () {};
else
complete = action;
action = opt;
opt = { };
} else if (typeof complete === 'undefined')
complete = function () {};
// Assert that dir is a string
if (typeof dir !== 'string')
dir = process.cwd();
opt = defaults(defaultOpt, opt);
// Check if user wants to ignore dir/file
// If they do, create function that can test if file matches
var ignore = null;
if (opt.ignore instanceof RegExp) {
ignore = function(file) { return file.match(opt.ignore); }
} else if (typeof opt.ignore === 'string' && opt.ignore.trim()) {
ignore = function(file) { return file.indexOf(opt.ignore) !== -1; }
}
function dive(dir) {
// Read the directory
todo++;
fs.readdir(dir, function(err, list) {
todo--;
// Return the error if something went wrong
if (err) {
action(err, dir);
} else {
// For every file in the list
list.forEach(function(file) {
if (ignore && ignore(file))
return;
if (opt.all || file[0] !== '.') {
// Full path of that file
var fullPath = path.resolve(dir, file);
// Get the file's stats
todo++;
fs.lstat(fullPath, function(err, stat) {
todo--;
if (err) {
action(err, fullPath);
} else {
if (stat) {
// If the file is a directory
if (stat.isDirectory()) {
// Call action if enabled for directories
if (opt.directories)
action(null, fullPath, stat);
// Dive into the directory
if (opt.recursive)
dive(fullPath);
} else {
// Call action if enabled for files
if (opt.files)
action(null, fullPath, stat);
}
}
}
if (!todo)
complete();
});
}
});
}
//empty directories, or with just hidden files
if (!todo)
complete();
});
}
var todo = 0;
dive(path.resolve(dir));
};