1 | import EE from 'events';
|
2 | import {inherits} from 'util';
|
3 |
|
4 | import {Duplex} from './duplex.js';
|
5 | import {Readable} from './readable.js';
|
6 | import {Writable} from './writable.js';
|
7 | import {Transform} from './transform.js';
|
8 | import {PassThrough} from './passthrough.js';
|
9 | inherits(Stream, EE);
|
10 | Stream.Readable = Readable;
|
11 | Stream.Writable = Writable;
|
12 | Stream.Duplex = Duplex;
|
13 | Stream.Transform = Transform;
|
14 | Stream.PassThrough = PassThrough;
|
15 |
|
16 |
|
17 | Stream.Stream = Stream;
|
18 |
|
19 | export default Stream;
|
20 | export {Readable,Writable,Duplex,Transform,PassThrough,Stream}
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | function Stream() {
|
26 | EE.call(this);
|
27 | }
|
28 |
|
29 | Stream.prototype.pipe = function(dest, options) {
|
30 | var source = this;
|
31 |
|
32 | function ondata(chunk) {
|
33 | if (dest.writable) {
|
34 | if (false === dest.write(chunk) && source.pause) {
|
35 | source.pause();
|
36 | }
|
37 | }
|
38 | }
|
39 |
|
40 | source.on('data', ondata);
|
41 |
|
42 | function ondrain() {
|
43 | if (source.readable && source.resume) {
|
44 | source.resume();
|
45 | }
|
46 | }
|
47 |
|
48 | dest.on('drain', ondrain);
|
49 |
|
50 |
|
51 |
|
52 | if (!dest._isStdio && (!options || options.end !== false)) {
|
53 | source.on('end', onend);
|
54 | source.on('close', onclose);
|
55 | }
|
56 |
|
57 | var didOnEnd = false;
|
58 | function onend() {
|
59 | if (didOnEnd) return;
|
60 | didOnEnd = true;
|
61 |
|
62 | dest.end();
|
63 | }
|
64 |
|
65 | function onclose() {
|
66 | if (didOnEnd) return;
|
67 | didOnEnd = true;
|
68 |
|
69 | if (typeof dest.destroy === 'function') dest.destroy();
|
70 | }
|
71 |
|
72 |
|
73 | function onerror(er) {
|
74 | cleanup();
|
75 | if (EE.listenerCount(this, 'error') === 0) {
|
76 | throw er;
|
77 | }
|
78 | }
|
79 |
|
80 | source.on('error', onerror);
|
81 | dest.on('error', onerror);
|
82 |
|
83 |
|
84 | function cleanup() {
|
85 | source.removeListener('data', ondata);
|
86 | dest.removeListener('drain', ondrain);
|
87 |
|
88 | source.removeListener('end', onend);
|
89 | source.removeListener('close', onclose);
|
90 |
|
91 | source.removeListener('error', onerror);
|
92 | dest.removeListener('error', onerror);
|
93 |
|
94 | source.removeListener('end', cleanup);
|
95 | source.removeListener('close', cleanup);
|
96 |
|
97 | dest.removeListener('close', cleanup);
|
98 | }
|
99 |
|
100 | source.on('end', cleanup);
|
101 | source.on('close', cleanup);
|
102 |
|
103 | dest.on('close', cleanup);
|
104 |
|
105 | dest.emit('pipe', source);
|
106 |
|
107 |
|
108 | return dest;
|
109 | };
|