This repository was archived by the owner on Jan 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrite-buffer.js
More file actions
72 lines (60 loc) · 1.42 KB
/
write-buffer.js
File metadata and controls
72 lines (60 loc) · 1.42 KB
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
var through = require('through');
module.exports = function (stream, size) {
if (stream.cork && stream._writev)
return cork(stream, size);
return buffer(stream, size);
};
module.exports.cork = cork;
module.exports.buffer = buffer;
/**
* Buffer in memory
* for streams without writev
*/
function buffer(output, size) {
var buf = null;
var input = through(write, end);
output.on('finish', input.emit.bind(input, 'finish'));
function write(data, encoding) {
if (!Buffer.isBuffer(data)) {
data = new Buffer(data, encoding);
}
buf = buf ? Buffer.concat([buf, data]) : data;
if (buf.length > size) {
output.write(buf);
buf = null;
}
}
function end() {
if (buf) output.write(buf);
output.end();
}
return input;
}
/**
* Buffer with cork()
* for streams with writev support
*/
function cork(output, size) {
var acc = 0;
var input = through(write, end);
output.cork();
output.on('finish', input.emit.bind(input, 'finish'));
function write(data, encoding, callback) {
acc += data.length;
if (acc > size) {
// do uncorked write
output.uncork();
output.write(data, encoding, callback);
// cork again
acc = 0;
output.cork();
} else {
// corked write
output.write(data, encoding, callback);
}
}
function end(data, encoding, callback) {
output.end(data, encoding, callback);
}
return input;
}