-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray-stream.js
37 lines (29 loc) · 1015 Bytes
/
array-stream.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
var util = require("util"),
Readable = require("stream").Readable;
var ArrayStream = function(arrayToSend, opts) {
Readable.call(this, opts);
if(arrayToSend === undefined)
throw new Error("No array provided.");
if(!Array.isArray(arrayToSend)) {
if(arrayToSend.constructor
&& arrayToSend.constructor.name)
throw new Error("Expected an Array to be passed as the data source, received %s.", arrayToSend.constructor.name);
throw new Error("Expected an Array to be passed as the data source.");
}
this.arrayToSend = arrayToSend.slice();
this.originalArray = arrayToSend.slice();
}
util.inherits(ArrayStream, Readable);
ArrayStream.prototype.reset = function() {
this.arrayToSend = this.originalArray.slice();
};
ArrayStream.prototype._read = function(size) {
var nextItem, bufferToSend;
do {
nextItem = this.arrayToSend.shift();
if(!nextItem)
return this.push(null);
bufferToSend = new Buffer(String(nextItem));
} while(this.push(bufferToSend));
};
module.exports = ArrayStream;