-
Notifications
You must be signed in to change notification settings - Fork 4
/
getFolderSize.js
118 lines (93 loc) · 2.42 KB
/
getFolderSize.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
110
111
112
113
114
115
116
117
118
const fs = require('fs')
const path = require('path')
function eachAsync(arr, parallelLimit, iteratorFn, cb) {
var pending = 0
var index = 0
var lastIndex = arr.length - 1
var called = false
var limit
var callback
var iterate
if (typeof parallelLimit === 'number') {
limit = parallelLimit
iterate = iteratorFn
callback = cb || function noop() {}
} else {
iterate = parallelLimit
callback = iteratorFn || function noop() {}
limit = arr.length
}
if (!arr.length) { return callback() }
var iteratorLength = iterate.length
var shouldCallNextIterator = function shouldCallNextIterator() {
return (!called && (pending < limit) && (index < lastIndex))
}
var iteratorCallback = function iteratorCallback(err) {
if (called) { return }
pending--
if (err || (index === lastIndex && !pending)) {
called = true
callback(err)
} else if (shouldCallNextIterator()) {
processIterator(++index)
}
}
var processIterator = function processIterator() {
pending++
var args = (iteratorLength === 2) ? [arr[index], iteratorCallback] : [arr[index], index, iteratorCallback]
iterate.apply(null, args)
if (shouldCallNextIterator()) {
processIterator(++index)
}
}
processIterator()
}
function readSizeRecursive(seen, item, ignoreRegEx, callback) {
let cb
let ignoreRegExp
if (!callback) {
cb = ignoreRegEx
ignoreRegExp = null
} else {
cb = callback
ignoreRegExp = ignoreRegEx
}
fs.lstat(item, function lstat(e, stats) {
let total = !e ? (stats.size || 0) : 0
if (stats) {
if (seen.has(stats.ino)) { return cb(null, 0) }
seen.add(stats.ino)
}
if (!e && stats.isDirectory()) {
fs.readdir(item, (err, list) => {
if (err) { return cb(err) }
eachAsync(
list,
(dirItem, next) => {
readSizeRecursive(
seen,
path.join(item, dirItem),
ignoreRegExp,
(error, size) => {
if (!error) { total += size }
next(error)
}
)
},
(finalErr) => {
cb(finalErr, total)
}
)
})
} else {
if (ignoreRegExp && ignoreRegExp.test(item)) {
total = 0
}
cb(e, total)
}
})
}
module.exports = (...args) => {
args.unshift(new Set())
return readSizeRecursive(...args)
}