-
Notifications
You must be signed in to change notification settings - Fork 25
/
12-streams.js
80 lines (63 loc) · 1.51 KB
/
12-streams.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
'use strict';
var numbers = [3, 1, 7];
var constant = 2;
function mul(a, b) {
return a * b;
}
function print(n) {
console.log(n);
}
var byConstant = mul.bind(null, constant);
// stream of numbers from an Array
var util = require('util');
var Readable = require('stream').Readable;
util.inherits(NumberStream, Readable);
function NumberStream(numbers) {
Readable.call(this, {
objectMode: true
});
this.numbers = numbers;
this.index = 0;
}
NumberStream.prototype._read = function _read() {
// utility functions for clarity
function outputNextNumber() {
this.push(this.numbers[this.index++]);
}
function isFinished() {
return this.index >= this.numbers.length;
}
outputNextNumber.call(this);
if (isFinished.call(this)) {
this.push(null);
}
};
// I like ending stream references with "_"
var numbers_ = new NumberStream(numbers);
// to just print the numbers do the following
/*
numbers_.on('data', print);
numbers_.on('end', function () {
console.log('numbers stream finished');
});*/
// number multiplier stream
var Transform = require('stream').Transform;
util.inherits(MultiplierStream, Transform);
function MultiplierStream(constant) {
Transform.call(this, {
objectMode: true
});
this.constant = constant;
}
MultiplierStream.prototype._transform =
function _transform(data, encoding, callback) {
this.push(data * this.constant);
callback();
};
var multiplier_ = new MultiplierStream(constant);
numbers_
.pipe(multiplier_)
.on('data', print);
// 6
// 2
// 14