forked from nodejs/node-v0.x-archive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream.js
363 lines (282 loc) · 8.85 KB
/
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
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module.exports = Stream;
var EE = require('events').EventEmitter;
var util = require('util');
var debug = util.debuglog('stream');
util.inherits(Stream, EE);
Stream.Readable = require('_stream_readable');
Stream.Writable = require('_stream_writable');
Stream.Duplex = require('_stream_duplex');
Stream.Transform = require('_stream_transform');
Stream.PassThrough = require('_stream_passthrough');
// Backwards-compat with node 0.4.x
Stream.Stream = Stream;
// old-style streams. Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.
function Stream() {
EE.call(this);
// note that we can't necessarily
// count on these attributes to be present
// on all streams -- some folk might subclass
// incorrectly.
this._nextStreams = [];
this._prevStreams = [];
this._errorHandlers = [];
}
Stream.prototype.next = function() {
if (!this._nextStreams) {
return [];
}
return this._nextStreams.slice();
};
Stream.prototype.prev = function() {
if (!this._prevStreams) {
return [];
}
return this._prevStreams.slice();
};
Stream.prototype.nextAll = function() {
return iterateStream(this, '_nextStreams');
};
Stream.prototype.prevAll = function() {
return iterateStream(this, '_prevStreams');
};
Stream.prototype.removePipelineErrorHandler = function(fn) {
if (!this._errorHandlers) return;
for (var i = 0, len = this._errorHandlers.length; i < len; ++i) {
if (this._errorHandlers[i].handler === fn) {
this._errorHandlers[i].uninstall();
return;
}
}
};
Stream.prototype.addPipelineErrorHandler = function(fn) {
if (!this._errorHandlers) {
this._errorHandlers = [];
}
var isHandling = true;
var installedOnStreams = [];
// Using a WeakSet + array pair to speed up
// membership lookups. Could be accomplished
// with just the array.
var installedMembership = new WeakSet;
var source = this;
install(this);
this.prevAll().forEach(install);
var installedIdx = this._errorHandlers.push({
handler: fn,
uninstall: uninstallAll
}) - 1;
return this;
function install(stream, idx, all) {
if (installedMembership.has(stream)) {
return;
}
installedOnStreams.push(stream);
installedMembership.add(stream);
stream.on('_preError', onPreError);
stream.on('unpipe', onunpipe);
stream.on('pipe', onpipe);
if (EE.listenerCount(stream, 'error') === 0) {
stream.on('error', _defaultPipelineErrorHandler);
}
}
function onpipe(newSrc) {
this.removeListener('error', _defaultPipelineErrorHandler);
install(newSrc);
newSrc.prevAll().forEach(install);
}
function onunpipe() {
uninstallAll();
source.addPipelineErrorHandler(fn);
}
function onPreError(err, handled) {
handled.handled = maybePropagate(this, err);
}
function uninstall(stream) {
stream.removeListener('_preError', onPreError);
stream.removeListener('error', _defaultPipelineErrorHandler);
stream.removeListener('pipe', onpipe);
stream.removeListener('unpipe', onunpipe);
installedMembership.delete(stream);
if (!stream._errorHandlers) return;
if (stream !== source) return;
if (installedIdx === null) return;
stream._errorHandlers.splice(installedIdx, 1);
installedIdx = null;
}
function uninstallAll() {
installedOnStreams.forEach(uninstall);
installedOnStreams.length = 0;
}
};
// the default pipeline error handler exists because
// streams2+ do not add an error handler to Readables on ".pipe".
// this catches any error that would otherwise be emitted.
function _defaultPipelineErrorHandler(err) {
var handled = {handled: false};
this.emit('_preError', err, handled);
if (handled.handled) {
return;
}
if (EE.listenerCount(this, 'error') === 1) {
this.removeListener('error', _defaultPipelineErrorHandler);
this.emit('error', err);
}
}
function maybePropagate(stream, error) {
var errorEvent = error._errorEvent;
var wasCreated = !errorEvent;
errorEvent = error._errorEvent = errorEvent ||
new PipelineErrorEvent(error, stream);
if (wasCreated) {
if (visit(stream)) {
return true;
}
return stream.nextAll().some(visit);
}
return errorEvent.isHandled();
function visit(xs, idx) {
if (!xs._errorHandlers) return;
if (!xs._errorHandlers.length) return;
return xs._errorHandlers.some(function(handlerPair) {
handlerPair.handler.call(xs, errorEvent);
return errorEvent.isHandled();
});
}
}
function iterateStream(stream, attr) {
var visited = new WeakSet;
var current = stream;
var stack = [stream];
var out = [];
while (stack.length) {
current = stack.pop();
if (visited.has(current)) {
continue;
}
visited.add(current);
out.push(current);
var children = attr in current ? current[attr] : [];
children = children || [];
for (var i = children.length - 1; i > -1; --i) {
stack.push(children[i]);
}
}
return out.slice(1);
}
Stream.prototype.pipe = function(dest, options) {
var source = this;
source._nextStreams = source._nextStreams || [];
dest._prevStreams = dest._prevStreams || [];
var nextIdx = source._nextStreams.push(dest) - 1;
var prevIdx = dest._prevStreams.push(source) - 1;
function ondata(chunk) {
if (dest.writable) {
if (false === dest.write(chunk) && source.pause) {
source.pause();
}
}
}
source.on('data', ondata);
function ondrain() {
if (source.readable && source.resume) {
source.resume();
}
}
dest.on('drain', ondrain);
// If the 'end' option is not supplied, dest.end() will be called when
// source gets the 'end' or 'close' events. Only dest.end() once.
if (!dest._isStdio && (!options || options.end !== false)) {
source.on('end', onend);
source.on('close', onclose);
}
var didOnEnd = false;
function onend() {
if (didOnEnd) return;
didOnEnd = true;
dest.end();
}
function onclose() {
if (didOnEnd) return;
didOnEnd = true;
if (util.isFunction(dest.destroy)) dest.destroy();
}
// don't leave dangling pipes when there are errors.
function onerror(er) {
var handled = {handled: false};
this.emit('_preError', er, handled);
if (handled.handled) {
return;
}
cleanup();
if (EE.listenerCount(this, 'error') === 0) {
throw er; // Unhandled stream error in pipe.
}
}
source.on('error', onerror);
dest.on('error', onerror);
// remove all the event listeners that were added.
function cleanup() {
source.removeListener('data', ondata);
dest.removeListener('drain', ondrain);
source.removeListener('end', onend);
source.removeListener('close', onclose);
source.removeListener('error', onerror);
dest.removeListener('error', onerror);
source.removeListener('end', cleanup);
source.removeListener('close', cleanup);
dest.removeListener('close', cleanup);
if (nextIdx !== null) {
source._nextStreams.splice(nextIdx, 1);
nextIdx = null;
}
if (prevIdx !== null) {
dest._prevStreams.splice(prevIdx, 1);
prevIdx = null;
}
}
source.on('end', cleanup);
source.on('close', cleanup);
dest.on('close', cleanup);
dest.emit('pipe', source);
// Allow for unix-like usage: A.pipe(B).pipe(C)
return dest;
};
var pipelineErrorState = new WeakMap;
function PipelineErrorEvent(err, sourceStream, unpipe) {
this.error = err;
this.stream = sourceStream;
pipelineErrorState.set(this, {
'isHandled': false
});
}
PipelineErrorEvent.prototype.handleError = function() {
debug('handleError', this.error);
pipelineErrorState.set(this, {
'isHandled': true
});
};
PipelineErrorEvent.prototype.isHandled = function() {
var state = pipelineErrorState.get(this) || {};
return Boolean(state.isHandled);
};