-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
69 lines (57 loc) · 1.49 KB
/
index.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
'use strict';
var Transform = require('stream').Transform,
inherits = require('util').inherits;
function noop() {}
function sanitizeArguments(options, done) {
if (done) {
// both args
return [options, done];
}
if (!options) {
// no args
return [{}, noop];
}
// one arg
if (typeof options === 'function') {
return [{}, options];
}
return [options, noop];
}
function StreamRecorder(/* [options], [done] */) {
if (!(this instanceof StreamRecorder)) {
return new StreamRecorder(arguments[0], arguments[1]);
}
var self = this,
args = sanitizeArguments.apply(null, arguments),
options = args[0],
done = args[1];
Transform.call(this, options);
this.objectMode = options.objectMode;
if (this.objectMode) {
this.buffer = [];
} else {
this.buffer = new Buffer('', options.encoding);
}
this.on('finish', function() {
done.call(self, self.buffer);
});
}
inherits(StreamRecorder, Transform);
StreamRecorder.prototype._transform = function(chunk, encoding, done) {
if (this.objectMode) {
this.buffer.push(chunk);
} else {
if (typeof chunk === 'string') {
chunk = new Buffer(chunk, encoding);
}
this.buffer = Buffer.concat([this.buffer, chunk]);
}
this.push(chunk, encoding);
done();
};
StreamRecorder.obj = function(/* [options], [done] */) {
var args = sanitizeArguments.apply(null, arguments);
args[0].objectMode = true;
return StreamRecorder.apply(null, args);
};
module.exports = StreamRecorder;