/
filetree.js
104 lines (83 loc) · 2.15 KB
/
filetree.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
var fs = require('fs');
module.exports = function (options) {
if ('depth' in options) {
delete options.depth;
}
return filetree(options);
};
function filetree(options) {
var path, maxDepth, exclude, all, indent, depth;
if (!options) {
options = {};
}
path = options.path;
maxDepth = options.maxDepth;
exclude = options.exclude;
all = options.all;
indent = options.indent;
depth = options.depth;
var i, j, l, out, file, isDir, stats, files;
stats = fs.lstatSync(path);
if (!stats.isDirectory()) {
throw new Error(path + ' must be a directory');
}
fs.accessSync(path, fs.R_OK);
if (typeof maxDepth !== 'number') {
maxDepth = -1;
}
if (!Array.isArray(exclude)) {
exclude = [];
}
exclude = exclude.map(function (name) {
return name.replace(/(^[\/\\]+|[\/\\]+$)/g, '');
});
if (typeof depth === 'undefined') {
depth = 0;
} else {
depth++;
}
files = fs.readdirSync(path);
for (i = 0, l = files.length; i < l; i++) {
if (exclude.indexOf(files[i]) >= 0) {
continue;
}
if (!all && files[i][0] === '.') {
continue;
}
file = path + '/' + files[i];
out = '';
if (indent) {
for (j = 0; j < depth; j++) {
out += ' ';
}
}
out += files[i];
try {
stats = fs.lstatSync(file);
} catch (e) {
console.log(out + ' (Does not exist)');
continue;
}
isDir = stats.isDirectory();
if (isDir) {
out += '/';
}
try {
fs.accessSync(file, fs.R_OK);
} catch (e) {
console.log(out + ' (No permission)');
continue;
}
console.log(out);
if (isDir && (maxDepth < 0 || depth < maxDepth)) {
filetree({
path: file,
maxDepth: maxDepth,
exclude: exclude,
all: all,
indent: indent,
depth: depth
});
}
}
}