-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathutil.js
58 lines (53 loc) · 1.12 KB
/
util.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
var through = require('through')
exports.stream2cb = function(stream, cb) {
var chunks = []
var complete
stream.on('data', function(d) {
chunks.push(d)
})
stream.on('end', function() {
if (!complete) {
complete = true
cb(null, Buffer.concat(chunks))
}
})
stream.on('error', function(e) {
if (!complete) {
complete = true
cb(e)
}
})
}
exports.chunkSizeSafe = function(size) {
var last
return through(function(d) {
if (last) d = Buffer.concat([last, d])
var end = Math.floor(d.length / size) * size
if (!end) {
last = last ? Buffer.concat([last, d]) : d
}
else if (d.length > end) {
last = d.slice(end)
this.emit('data', d.slice(0, end))
}
else {
last = undefined
this.emit('data', d)
}
}, function() {
if (last) this.emit('data', last)
this.emit('end')
})
}
exports.detectSize = function(cb) {
var chunks = []
var size = 0
return through(function(d) {
chunks.push(d)
size += d.length
}, function() {
cb(size)
chunks.forEach(this.emit.bind(this, 'data'))
this.emit('end')
})
}