-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdir-tree-creator.js
64 lines (58 loc) · 1.49 KB
/
dir-tree-creator.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
'use strict'
const path = require('path')
const archy = require('archy')
const klaw = require('klaw')
function addNode (tree, par, node) {
if (par === tree.label) {
tree.nodes.push({
label: node,
nodes: []
})
} else {
tree.nodes.forEach(n => {
if (typeof n === 'object' && n.label === par) {
n.nodes.push({
label: node,
nodes: []
})
} else if (typeof n === 'object' && n.label !== par) {
addNode(n, par, node)
}
})
}
}
function dirTree (root, opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
opts.label = opts.label || path.basename(root)
opts.hidden = typeof opts.hidden !== 'undefined' ? opts.hidden : true
const paths = []
const filterFunc = item => {
if (!opts.hidden) {
const basename = path.basename(item)
return basename === '.' || basename[0] !== '.'
} else {
return true
}
}
klaw(root, { filter: filterFunc }).on('error', er => cb(er)).on('data', i => paths.push(i.path))
.on('end', () => {
const tree = {
label: opts.label,
nodes: []
}
for (var i = 0; i < paths.length; i += 1) {
const p = paths[i]
const par = path.dirname(p)
if (par === root) {
addNode(tree, opts.label, path.basename(p))
} else {
addNode(tree, path.basename(par), path.basename(p))
}
}
return cb(null, archy(tree).trim())
})
}
module.exports = dirTree