source: frontend/node_modules/readable-stream/lib/_stream_readable.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 35.2 KB
Line 
1// Copyright Joyent, Inc. and other Node contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to permit
8// persons to whom the Software is furnished to do so, subject to the
9// following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22'use strict';
23
24module.exports = Readable;
25
26/*<replacement>*/
27var Duplex;
28/*</replacement>*/
29
30Readable.ReadableState = ReadableState;
31
32/*<replacement>*/
33var EE = require('events').EventEmitter;
34var EElistenerCount = function EElistenerCount(emitter, type) {
35 return emitter.listeners(type).length;
36};
37/*</replacement>*/
38
39/*<replacement>*/
40var Stream = require('./internal/streams/stream');
41/*</replacement>*/
42
43var Buffer = require('buffer').Buffer;
44var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
45function _uint8ArrayToBuffer(chunk) {
46 return Buffer.from(chunk);
47}
48function _isUint8Array(obj) {
49 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
50}
51
52/*<replacement>*/
53var debugUtil = require('util');
54var debug;
55if (debugUtil && debugUtil.debuglog) {
56 debug = debugUtil.debuglog('stream');
57} else {
58 debug = function debug() {};
59}
60/*</replacement>*/
61
62var BufferList = require('./internal/streams/buffer_list');
63var destroyImpl = require('./internal/streams/destroy');
64var _require = require('./internal/streams/state'),
65 getHighWaterMark = _require.getHighWaterMark;
66var _require$codes = require('../errors').codes,
67 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
68 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
69 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
70 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
71
72// Lazy loaded to improve the startup performance.
73var StringDecoder;
74var createReadableStreamAsyncIterator;
75var from;
76require('inherits')(Readable, Stream);
77var errorOrDestroy = destroyImpl.errorOrDestroy;
78var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
79function prependListener(emitter, event, fn) {
80 // Sadly this is not cacheable as some libraries bundle their own
81 // event emitter implementation with them.
82 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
83
84 // This is a hack to make sure that our error handler is attached before any
85 // userland ones. NEVER DO THIS. This is here only because this code needs
86 // to continue to work with older versions of Node.js that do not include
87 // the prependListener() method. The goal is to eventually remove this hack.
88 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
89}
90function ReadableState(options, stream, isDuplex) {
91 Duplex = Duplex || require('./_stream_duplex');
92 options = options || {};
93
94 // Duplex streams are both readable and writable, but share
95 // the same options object.
96 // However, some cases require setting options to different
97 // values for the readable and the writable sides of the duplex stream.
98 // These options can be provided separately as readableXXX and writableXXX.
99 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
100
101 // object stream flag. Used to make read(n) ignore n and to
102 // make all the buffer merging and length checks go away
103 this.objectMode = !!options.objectMode;
104 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
105
106 // the point at which it stops calling _read() to fill the buffer
107 // Note: 0 is a valid value, means "don't call _read preemptively ever"
108 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex);
109
110 // A linked list is used to store data chunks instead of an array because the
111 // linked list can remove elements from the beginning faster than
112 // array.shift()
113 this.buffer = new BufferList();
114 this.length = 0;
115 this.pipes = null;
116 this.pipesCount = 0;
117 this.flowing = null;
118 this.ended = false;
119 this.endEmitted = false;
120 this.reading = false;
121
122 // a flag to be able to tell if the event 'readable'/'data' is emitted
123 // immediately, or on a later tick. We set this to true at first, because
124 // any actions that shouldn't happen until "later" should generally also
125 // not happen before the first read call.
126 this.sync = true;
127
128 // whenever we return null, then we set a flag to say
129 // that we're awaiting a 'readable' event emission.
130 this.needReadable = false;
131 this.emittedReadable = false;
132 this.readableListening = false;
133 this.resumeScheduled = false;
134 this.paused = true;
135
136 // Should close be emitted on destroy. Defaults to true.
137 this.emitClose = options.emitClose !== false;
138
139 // Should .destroy() be called after 'end' (and potentially 'finish')
140 this.autoDestroy = !!options.autoDestroy;
141
142 // has it been destroyed
143 this.destroyed = false;
144
145 // Crypto is kind of old and crusty. Historically, its default string
146 // encoding is 'binary' so we have to make this configurable.
147 // Everything else in the universe uses 'utf8', though.
148 this.defaultEncoding = options.defaultEncoding || 'utf8';
149
150 // the number of writers that are awaiting a drain event in .pipe()s
151 this.awaitDrain = 0;
152
153 // if true, a maybeReadMore has been scheduled
154 this.readingMore = false;
155 this.decoder = null;
156 this.encoding = null;
157 if (options.encoding) {
158 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
159 this.decoder = new StringDecoder(options.encoding);
160 this.encoding = options.encoding;
161 }
162}
163function Readable(options) {
164 Duplex = Duplex || require('./_stream_duplex');
165 if (!(this instanceof Readable)) return new Readable(options);
166
167 // Checking for a Stream.Duplex instance is faster here instead of inside
168 // the ReadableState constructor, at least with V8 6.5
169 var isDuplex = this instanceof Duplex;
170 this._readableState = new ReadableState(options, this, isDuplex);
171
172 // legacy
173 this.readable = true;
174 if (options) {
175 if (typeof options.read === 'function') this._read = options.read;
176 if (typeof options.destroy === 'function') this._destroy = options.destroy;
177 }
178 Stream.call(this);
179}
180Object.defineProperty(Readable.prototype, 'destroyed', {
181 // making it explicit this property is not enumerable
182 // because otherwise some prototype manipulation in
183 // userland will fail
184 enumerable: false,
185 get: function get() {
186 if (this._readableState === undefined) {
187 return false;
188 }
189 return this._readableState.destroyed;
190 },
191 set: function set(value) {
192 // we ignore the value if the stream
193 // has not been initialized yet
194 if (!this._readableState) {
195 return;
196 }
197
198 // backward compatibility, the user is explicitly
199 // managing destroyed
200 this._readableState.destroyed = value;
201 }
202});
203Readable.prototype.destroy = destroyImpl.destroy;
204Readable.prototype._undestroy = destroyImpl.undestroy;
205Readable.prototype._destroy = function (err, cb) {
206 cb(err);
207};
208
209// Manually shove something into the read() buffer.
210// This returns true if the highWaterMark has not been hit yet,
211// similar to how Writable.write() returns true if you should
212// write() some more.
213Readable.prototype.push = function (chunk, encoding) {
214 var state = this._readableState;
215 var skipChunkCheck;
216 if (!state.objectMode) {
217 if (typeof chunk === 'string') {
218 encoding = encoding || state.defaultEncoding;
219 if (encoding !== state.encoding) {
220 chunk = Buffer.from(chunk, encoding);
221 encoding = '';
222 }
223 skipChunkCheck = true;
224 }
225 } else {
226 skipChunkCheck = true;
227 }
228 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
229};
230
231// Unshift should *always* be something directly out of read()
232Readable.prototype.unshift = function (chunk) {
233 return readableAddChunk(this, chunk, null, true, false);
234};
235function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
236 debug('readableAddChunk', chunk);
237 var state = stream._readableState;
238 if (chunk === null) {
239 state.reading = false;
240 onEofChunk(stream, state);
241 } else {
242 var er;
243 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
244 if (er) {
245 errorOrDestroy(stream, er);
246 } else if (state.objectMode || chunk && chunk.length > 0) {
247 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
248 chunk = _uint8ArrayToBuffer(chunk);
249 }
250 if (addToFront) {
251 if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
252 } else if (state.ended) {
253 errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
254 } else if (state.destroyed) {
255 return false;
256 } else {
257 state.reading = false;
258 if (state.decoder && !encoding) {
259 chunk = state.decoder.write(chunk);
260 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
261 } else {
262 addChunk(stream, state, chunk, false);
263 }
264 }
265 } else if (!addToFront) {
266 state.reading = false;
267 maybeReadMore(stream, state);
268 }
269 }
270
271 // We can push more data if we are below the highWaterMark.
272 // Also, if we have no data yet, we can stand some more bytes.
273 // This is to work around cases where hwm=0, such as the repl.
274 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
275}
276function addChunk(stream, state, chunk, addToFront) {
277 if (state.flowing && state.length === 0 && !state.sync) {
278 state.awaitDrain = 0;
279 stream.emit('data', chunk);
280 } else {
281 // update the buffer info.
282 state.length += state.objectMode ? 1 : chunk.length;
283 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
284 if (state.needReadable) emitReadable(stream);
285 }
286 maybeReadMore(stream, state);
287}
288function chunkInvalid(state, chunk) {
289 var er;
290 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
291 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
292 }
293 return er;
294}
295Readable.prototype.isPaused = function () {
296 return this._readableState.flowing === false;
297};
298
299// backwards compatibility.
300Readable.prototype.setEncoding = function (enc) {
301 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
302 var decoder = new StringDecoder(enc);
303 this._readableState.decoder = decoder;
304 // If setEncoding(null), decoder.encoding equals utf8
305 this._readableState.encoding = this._readableState.decoder.encoding;
306
307 // Iterate over current buffer to convert already stored Buffers:
308 var p = this._readableState.buffer.head;
309 var content = '';
310 while (p !== null) {
311 content += decoder.write(p.data);
312 p = p.next;
313 }
314 this._readableState.buffer.clear();
315 if (content !== '') this._readableState.buffer.push(content);
316 this._readableState.length = content.length;
317 return this;
318};
319
320// Don't raise the hwm > 1GB
321var MAX_HWM = 0x40000000;
322function computeNewHighWaterMark(n) {
323 if (n >= MAX_HWM) {
324 // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
325 n = MAX_HWM;
326 } else {
327 // Get the next highest power of 2 to prevent increasing hwm excessively in
328 // tiny amounts
329 n--;
330 n |= n >>> 1;
331 n |= n >>> 2;
332 n |= n >>> 4;
333 n |= n >>> 8;
334 n |= n >>> 16;
335 n++;
336 }
337 return n;
338}
339
340// This function is designed to be inlinable, so please take care when making
341// changes to the function body.
342function howMuchToRead(n, state) {
343 if (n <= 0 || state.length === 0 && state.ended) return 0;
344 if (state.objectMode) return 1;
345 if (n !== n) {
346 // Only flow one buffer at a time
347 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
348 }
349 // If we're asking for more than the current hwm, then raise the hwm.
350 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
351 if (n <= state.length) return n;
352 // Don't have enough
353 if (!state.ended) {
354 state.needReadable = true;
355 return 0;
356 }
357 return state.length;
358}
359
360// you can override either this method, or the async _read(n) below.
361Readable.prototype.read = function (n) {
362 debug('read', n);
363 n = parseInt(n, 10);
364 var state = this._readableState;
365 var nOrig = n;
366 if (n !== 0) state.emittedReadable = false;
367
368 // if we're doing read(0) to trigger a readable event, but we
369 // already have a bunch of data in the buffer, then just trigger
370 // the 'readable' event and move on.
371 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
372 debug('read: emitReadable', state.length, state.ended);
373 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
374 return null;
375 }
376 n = howMuchToRead(n, state);
377
378 // if we've ended, and we're now clear, then finish it up.
379 if (n === 0 && state.ended) {
380 if (state.length === 0) endReadable(this);
381 return null;
382 }
383
384 // All the actual chunk generation logic needs to be
385 // *below* the call to _read. The reason is that in certain
386 // synthetic stream cases, such as passthrough streams, _read
387 // may be a completely synchronous operation which may change
388 // the state of the read buffer, providing enough data when
389 // before there was *not* enough.
390 //
391 // So, the steps are:
392 // 1. Figure out what the state of things will be after we do
393 // a read from the buffer.
394 //
395 // 2. If that resulting state will trigger a _read, then call _read.
396 // Note that this may be asynchronous, or synchronous. Yes, it is
397 // deeply ugly to write APIs this way, but that still doesn't mean
398 // that the Readable class should behave improperly, as streams are
399 // designed to be sync/async agnostic.
400 // Take note if the _read call is sync or async (ie, if the read call
401 // has returned yet), so that we know whether or not it's safe to emit
402 // 'readable' etc.
403 //
404 // 3. Actually pull the requested chunks out of the buffer and return.
405
406 // if we need a readable event, then we need to do some reading.
407 var doRead = state.needReadable;
408 debug('need readable', doRead);
409
410 // if we currently have less than the highWaterMark, then also read some
411 if (state.length === 0 || state.length - n < state.highWaterMark) {
412 doRead = true;
413 debug('length less than watermark', doRead);
414 }
415
416 // however, if we've ended, then there's no point, and if we're already
417 // reading, then it's unnecessary.
418 if (state.ended || state.reading) {
419 doRead = false;
420 debug('reading or ended', doRead);
421 } else if (doRead) {
422 debug('do read');
423 state.reading = true;
424 state.sync = true;
425 // if the length is currently zero, then we *need* a readable event.
426 if (state.length === 0) state.needReadable = true;
427 // call internal read method
428 this._read(state.highWaterMark);
429 state.sync = false;
430 // If _read pushed data synchronously, then `reading` will be false,
431 // and we need to re-evaluate how much data we can return to the user.
432 if (!state.reading) n = howMuchToRead(nOrig, state);
433 }
434 var ret;
435 if (n > 0) ret = fromList(n, state);else ret = null;
436 if (ret === null) {
437 state.needReadable = state.length <= state.highWaterMark;
438 n = 0;
439 } else {
440 state.length -= n;
441 state.awaitDrain = 0;
442 }
443 if (state.length === 0) {
444 // If we have nothing in the buffer, then we want to know
445 // as soon as we *do* get something into the buffer.
446 if (!state.ended) state.needReadable = true;
447
448 // If we tried to read() past the EOF, then emit end on the next tick.
449 if (nOrig !== n && state.ended) endReadable(this);
450 }
451 if (ret !== null) this.emit('data', ret);
452 return ret;
453};
454function onEofChunk(stream, state) {
455 debug('onEofChunk');
456 if (state.ended) return;
457 if (state.decoder) {
458 var chunk = state.decoder.end();
459 if (chunk && chunk.length) {
460 state.buffer.push(chunk);
461 state.length += state.objectMode ? 1 : chunk.length;
462 }
463 }
464 state.ended = true;
465 if (state.sync) {
466 // if we are sync, wait until next tick to emit the data.
467 // Otherwise we risk emitting data in the flow()
468 // the readable code triggers during a read() call
469 emitReadable(stream);
470 } else {
471 // emit 'readable' now to make sure it gets picked up.
472 state.needReadable = false;
473 if (!state.emittedReadable) {
474 state.emittedReadable = true;
475 emitReadable_(stream);
476 }
477 }
478}
479
480// Don't emit readable right away in sync mode, because this can trigger
481// another read() call => stack overflow. This way, it might trigger
482// a nextTick recursion warning, but that's not so bad.
483function emitReadable(stream) {
484 var state = stream._readableState;
485 debug('emitReadable', state.needReadable, state.emittedReadable);
486 state.needReadable = false;
487 if (!state.emittedReadable) {
488 debug('emitReadable', state.flowing);
489 state.emittedReadable = true;
490 process.nextTick(emitReadable_, stream);
491 }
492}
493function emitReadable_(stream) {
494 var state = stream._readableState;
495 debug('emitReadable_', state.destroyed, state.length, state.ended);
496 if (!state.destroyed && (state.length || state.ended)) {
497 stream.emit('readable');
498 state.emittedReadable = false;
499 }
500
501 // The stream needs another readable event if
502 // 1. It is not flowing, as the flow mechanism will take
503 // care of it.
504 // 2. It is not ended.
505 // 3. It is below the highWaterMark, so we can schedule
506 // another readable later.
507 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
508 flow(stream);
509}
510
511// at this point, the user has presumably seen the 'readable' event,
512// and called read() to consume some data. that may have triggered
513// in turn another _read(n) call, in which case reading = true if
514// it's in progress.
515// However, if we're not ended, or reading, and the length < hwm,
516// then go ahead and try to read some more preemptively.
517function maybeReadMore(stream, state) {
518 if (!state.readingMore) {
519 state.readingMore = true;
520 process.nextTick(maybeReadMore_, stream, state);
521 }
522}
523function maybeReadMore_(stream, state) {
524 // Attempt to read more data if we should.
525 //
526 // The conditions for reading more data are (one of):
527 // - Not enough data buffered (state.length < state.highWaterMark). The loop
528 // is responsible for filling the buffer with enough data if such data
529 // is available. If highWaterMark is 0 and we are not in the flowing mode
530 // we should _not_ attempt to buffer any extra data. We'll get more data
531 // when the stream consumer calls read() instead.
532 // - No data in the buffer, and the stream is in flowing mode. In this mode
533 // the loop below is responsible for ensuring read() is called. Failing to
534 // call read here would abort the flow and there's no other mechanism for
535 // continuing the flow if the stream consumer has just subscribed to the
536 // 'data' event.
537 //
538 // In addition to the above conditions to keep reading data, the following
539 // conditions prevent the data from being read:
540 // - The stream has ended (state.ended).
541 // - There is already a pending 'read' operation (state.reading). This is a
542 // case where the the stream has called the implementation defined _read()
543 // method, but they are processing the call asynchronously and have _not_
544 // called push() with new data. In this case we skip performing more
545 // read()s. The execution ends in this method again after the _read() ends
546 // up calling push() with more data.
547 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
548 var len = state.length;
549 debug('maybeReadMore read 0');
550 stream.read(0);
551 if (len === state.length)
552 // didn't get any data, stop spinning.
553 break;
554 }
555 state.readingMore = false;
556}
557
558// abstract method. to be overridden in specific implementation classes.
559// call cb(er, data) where data is <= n in length.
560// for virtual (non-string, non-buffer) streams, "length" is somewhat
561// arbitrary, and perhaps not very meaningful.
562Readable.prototype._read = function (n) {
563 errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
564};
565Readable.prototype.pipe = function (dest, pipeOpts) {
566 var src = this;
567 var state = this._readableState;
568 switch (state.pipesCount) {
569 case 0:
570 state.pipes = dest;
571 break;
572 case 1:
573 state.pipes = [state.pipes, dest];
574 break;
575 default:
576 state.pipes.push(dest);
577 break;
578 }
579 state.pipesCount += 1;
580 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
581 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
582 var endFn = doEnd ? onend : unpipe;
583 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
584 dest.on('unpipe', onunpipe);
585 function onunpipe(readable, unpipeInfo) {
586 debug('onunpipe');
587 if (readable === src) {
588 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
589 unpipeInfo.hasUnpiped = true;
590 cleanup();
591 }
592 }
593 }
594 function onend() {
595 debug('onend');
596 dest.end();
597 }
598
599 // when the dest drains, it reduces the awaitDrain counter
600 // on the source. This would be more elegant with a .once()
601 // handler in flow(), but adding and removing repeatedly is
602 // too slow.
603 var ondrain = pipeOnDrain(src);
604 dest.on('drain', ondrain);
605 var cleanedUp = false;
606 function cleanup() {
607 debug('cleanup');
608 // cleanup event handlers once the pipe is broken
609 dest.removeListener('close', onclose);
610 dest.removeListener('finish', onfinish);
611 dest.removeListener('drain', ondrain);
612 dest.removeListener('error', onerror);
613 dest.removeListener('unpipe', onunpipe);
614 src.removeListener('end', onend);
615 src.removeListener('end', unpipe);
616 src.removeListener('data', ondata);
617 cleanedUp = true;
618
619 // if the reader is waiting for a drain event from this
620 // specific writer, then it would cause it to never start
621 // flowing again.
622 // So, if this is awaiting a drain, then we just call it now.
623 // If we don't know, then assume that we are waiting for one.
624 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
625 }
626 src.on('data', ondata);
627 function ondata(chunk) {
628 debug('ondata');
629 var ret = dest.write(chunk);
630 debug('dest.write', ret);
631 if (ret === false) {
632 // If the user unpiped during `dest.write()`, it is possible
633 // to get stuck in a permanently paused state if that write
634 // also returned false.
635 // => Check whether `dest` is still a piping destination.
636 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
637 debug('false write response, pause', state.awaitDrain);
638 state.awaitDrain++;
639 }
640 src.pause();
641 }
642 }
643
644 // if the dest has an error, then stop piping into it.
645 // however, don't suppress the throwing behavior for this.
646 function onerror(er) {
647 debug('onerror', er);
648 unpipe();
649 dest.removeListener('error', onerror);
650 if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
651 }
652
653 // Make sure our error handler is attached before userland ones.
654 prependListener(dest, 'error', onerror);
655
656 // Both close and finish should trigger unpipe, but only once.
657 function onclose() {
658 dest.removeListener('finish', onfinish);
659 unpipe();
660 }
661 dest.once('close', onclose);
662 function onfinish() {
663 debug('onfinish');
664 dest.removeListener('close', onclose);
665 unpipe();
666 }
667 dest.once('finish', onfinish);
668 function unpipe() {
669 debug('unpipe');
670 src.unpipe(dest);
671 }
672
673 // tell the dest that it's being piped to
674 dest.emit('pipe', src);
675
676 // start the flow if it hasn't been started already.
677 if (!state.flowing) {
678 debug('pipe resume');
679 src.resume();
680 }
681 return dest;
682};
683function pipeOnDrain(src) {
684 return function pipeOnDrainFunctionResult() {
685 var state = src._readableState;
686 debug('pipeOnDrain', state.awaitDrain);
687 if (state.awaitDrain) state.awaitDrain--;
688 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
689 state.flowing = true;
690 flow(src);
691 }
692 };
693}
694Readable.prototype.unpipe = function (dest) {
695 var state = this._readableState;
696 var unpipeInfo = {
697 hasUnpiped: false
698 };
699
700 // if we're not piping anywhere, then do nothing.
701 if (state.pipesCount === 0) return this;
702
703 // just one destination. most common case.
704 if (state.pipesCount === 1) {
705 // passed in one, but it's not the right one.
706 if (dest && dest !== state.pipes) return this;
707 if (!dest) dest = state.pipes;
708
709 // got a match.
710 state.pipes = null;
711 state.pipesCount = 0;
712 state.flowing = false;
713 if (dest) dest.emit('unpipe', this, unpipeInfo);
714 return this;
715 }
716
717 // slow case. multiple pipe destinations.
718
719 if (!dest) {
720 // remove all.
721 var dests = state.pipes;
722 var len = state.pipesCount;
723 state.pipes = null;
724 state.pipesCount = 0;
725 state.flowing = false;
726 for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, {
727 hasUnpiped: false
728 });
729 return this;
730 }
731
732 // try to find the right one.
733 var index = indexOf(state.pipes, dest);
734 if (index === -1) return this;
735 state.pipes.splice(index, 1);
736 state.pipesCount -= 1;
737 if (state.pipesCount === 1) state.pipes = state.pipes[0];
738 dest.emit('unpipe', this, unpipeInfo);
739 return this;
740};
741
742// set up data events if they are asked for
743// Ensure readable listeners eventually get something
744Readable.prototype.on = function (ev, fn) {
745 var res = Stream.prototype.on.call(this, ev, fn);
746 var state = this._readableState;
747 if (ev === 'data') {
748 // update readableListening so that resume() may be a no-op
749 // a few lines down. This is needed to support once('readable').
750 state.readableListening = this.listenerCount('readable') > 0;
751
752 // Try start flowing on next tick if stream isn't explicitly paused
753 if (state.flowing !== false) this.resume();
754 } else if (ev === 'readable') {
755 if (!state.endEmitted && !state.readableListening) {
756 state.readableListening = state.needReadable = true;
757 state.flowing = false;
758 state.emittedReadable = false;
759 debug('on readable', state.length, state.reading);
760 if (state.length) {
761 emitReadable(this);
762 } else if (!state.reading) {
763 process.nextTick(nReadingNextTick, this);
764 }
765 }
766 }
767 return res;
768};
769Readable.prototype.addListener = Readable.prototype.on;
770Readable.prototype.removeListener = function (ev, fn) {
771 var res = Stream.prototype.removeListener.call(this, ev, fn);
772 if (ev === 'readable') {
773 // We need to check if there is someone still listening to
774 // readable and reset the state. However this needs to happen
775 // after readable has been emitted but before I/O (nextTick) to
776 // support once('readable', fn) cycles. This means that calling
777 // resume within the same tick will have no
778 // effect.
779 process.nextTick(updateReadableListening, this);
780 }
781 return res;
782};
783Readable.prototype.removeAllListeners = function (ev) {
784 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
785 if (ev === 'readable' || ev === undefined) {
786 // We need to check if there is someone still listening to
787 // readable and reset the state. However this needs to happen
788 // after readable has been emitted but before I/O (nextTick) to
789 // support once('readable', fn) cycles. This means that calling
790 // resume within the same tick will have no
791 // effect.
792 process.nextTick(updateReadableListening, this);
793 }
794 return res;
795};
796function updateReadableListening(self) {
797 var state = self._readableState;
798 state.readableListening = self.listenerCount('readable') > 0;
799 if (state.resumeScheduled && !state.paused) {
800 // flowing needs to be set to true now, otherwise
801 // the upcoming resume will not flow.
802 state.flowing = true;
803
804 // crude way to check if we should resume
805 } else if (self.listenerCount('data') > 0) {
806 self.resume();
807 }
808}
809function nReadingNextTick(self) {
810 debug('readable nexttick read 0');
811 self.read(0);
812}
813
814// pause() and resume() are remnants of the legacy readable stream API
815// If the user uses them, then switch into old mode.
816Readable.prototype.resume = function () {
817 var state = this._readableState;
818 if (!state.flowing) {
819 debug('resume');
820 // we flow only if there is no one listening
821 // for readable, but we still have to call
822 // resume()
823 state.flowing = !state.readableListening;
824 resume(this, state);
825 }
826 state.paused = false;
827 return this;
828};
829function resume(stream, state) {
830 if (!state.resumeScheduled) {
831 state.resumeScheduled = true;
832 process.nextTick(resume_, stream, state);
833 }
834}
835function resume_(stream, state) {
836 debug('resume', state.reading);
837 if (!state.reading) {
838 stream.read(0);
839 }
840 state.resumeScheduled = false;
841 stream.emit('resume');
842 flow(stream);
843 if (state.flowing && !state.reading) stream.read(0);
844}
845Readable.prototype.pause = function () {
846 debug('call pause flowing=%j', this._readableState.flowing);
847 if (this._readableState.flowing !== false) {
848 debug('pause');
849 this._readableState.flowing = false;
850 this.emit('pause');
851 }
852 this._readableState.paused = true;
853 return this;
854};
855function flow(stream) {
856 var state = stream._readableState;
857 debug('flow', state.flowing);
858 while (state.flowing && stream.read() !== null);
859}
860
861// wrap an old-style stream as the async data source.
862// This is *not* part of the readable stream interface.
863// It is an ugly unfortunate mess of history.
864Readable.prototype.wrap = function (stream) {
865 var _this = this;
866 var state = this._readableState;
867 var paused = false;
868 stream.on('end', function () {
869 debug('wrapped end');
870 if (state.decoder && !state.ended) {
871 var chunk = state.decoder.end();
872 if (chunk && chunk.length) _this.push(chunk);
873 }
874 _this.push(null);
875 });
876 stream.on('data', function (chunk) {
877 debug('wrapped data');
878 if (state.decoder) chunk = state.decoder.write(chunk);
879
880 // don't skip over falsy values in objectMode
881 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
882 var ret = _this.push(chunk);
883 if (!ret) {
884 paused = true;
885 stream.pause();
886 }
887 });
888
889 // proxy all the other methods.
890 // important when wrapping filters and duplexes.
891 for (var i in stream) {
892 if (this[i] === undefined && typeof stream[i] === 'function') {
893 this[i] = function methodWrap(method) {
894 return function methodWrapReturnFunction() {
895 return stream[method].apply(stream, arguments);
896 };
897 }(i);
898 }
899 }
900
901 // proxy certain important events.
902 for (var n = 0; n < kProxyEvents.length; n++) {
903 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
904 }
905
906 // when we try to consume some more bytes, simply unpause the
907 // underlying stream.
908 this._read = function (n) {
909 debug('wrapped _read', n);
910 if (paused) {
911 paused = false;
912 stream.resume();
913 }
914 };
915 return this;
916};
917if (typeof Symbol === 'function') {
918 Readable.prototype[Symbol.asyncIterator] = function () {
919 if (createReadableStreamAsyncIterator === undefined) {
920 createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
921 }
922 return createReadableStreamAsyncIterator(this);
923 };
924}
925Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
926 // making it explicit this property is not enumerable
927 // because otherwise some prototype manipulation in
928 // userland will fail
929 enumerable: false,
930 get: function get() {
931 return this._readableState.highWaterMark;
932 }
933});
934Object.defineProperty(Readable.prototype, 'readableBuffer', {
935 // making it explicit this property is not enumerable
936 // because otherwise some prototype manipulation in
937 // userland will fail
938 enumerable: false,
939 get: function get() {
940 return this._readableState && this._readableState.buffer;
941 }
942});
943Object.defineProperty(Readable.prototype, 'readableFlowing', {
944 // making it explicit this property is not enumerable
945 // because otherwise some prototype manipulation in
946 // userland will fail
947 enumerable: false,
948 get: function get() {
949 return this._readableState.flowing;
950 },
951 set: function set(state) {
952 if (this._readableState) {
953 this._readableState.flowing = state;
954 }
955 }
956});
957
958// exposed for testing purposes only.
959Readable._fromList = fromList;
960Object.defineProperty(Readable.prototype, 'readableLength', {
961 // making it explicit this property is not enumerable
962 // because otherwise some prototype manipulation in
963 // userland will fail
964 enumerable: false,
965 get: function get() {
966 return this._readableState.length;
967 }
968});
969
970// Pluck off n bytes from an array of buffers.
971// Length is the combined lengths of all the buffers in the list.
972// This function is designed to be inlinable, so please take care when making
973// changes to the function body.
974function fromList(n, state) {
975 // nothing buffered
976 if (state.length === 0) return null;
977 var ret;
978 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
979 // read it all, truncate the list
980 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
981 state.buffer.clear();
982 } else {
983 // read part of list
984 ret = state.buffer.consume(n, state.decoder);
985 }
986 return ret;
987}
988function endReadable(stream) {
989 var state = stream._readableState;
990 debug('endReadable', state.endEmitted);
991 if (!state.endEmitted) {
992 state.ended = true;
993 process.nextTick(endReadableNT, state, stream);
994 }
995}
996function endReadableNT(state, stream) {
997 debug('endReadableNT', state.endEmitted, state.length);
998
999 // Check that we didn't get one last unshift.
1000 if (!state.endEmitted && state.length === 0) {
1001 state.endEmitted = true;
1002 stream.readable = false;
1003 stream.emit('end');
1004 if (state.autoDestroy) {
1005 // In case of duplex streams we need a way to detect
1006 // if the writable side is ready for autoDestroy as well
1007 var wState = stream._writableState;
1008 if (!wState || wState.autoDestroy && wState.finished) {
1009 stream.destroy();
1010 }
1011 }
1012 }
1013}
1014if (typeof Symbol === 'function') {
1015 Readable.from = function (iterable, opts) {
1016 if (from === undefined) {
1017 from = require('./internal/streams/from');
1018 }
1019 return from(Readable, iterable, opts);
1020 };
1021}
1022function indexOf(xs, x) {
1023 for (var i = 0, l = xs.length; i < l; i++) {
1024 if (xs[i] === x) return i;
1025 }
1026 return -1;
1027}
Note: See TracBrowser for help on using the repository browser.