_stream_readable.js 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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. 'use strict';
  22. /*<replacement>*/
  23. var processNextTick = require('process-nextick-args');
  24. /*</replacement>*/
  25. module.exports = Readable;
  26. /*<replacement>*/
  27. var isArray = require('isarray');
  28. /*</replacement>*/
  29. /*<replacement>*/
  30. var Duplex;
  31. /*</replacement>*/
  32. Readable.ReadableState = ReadableState;
  33. /*<replacement>*/
  34. var EE = require('events').EventEmitter;
  35. var EElistenerCount = function (emitter, type) {
  36. return emitter.listeners(type).length;
  37. };
  38. /*</replacement>*/
  39. /*<replacement>*/
  40. var Stream = require('./internal/streams/stream');
  41. /*</replacement>*/
  42. // TODO(bmeurer): Change this back to const once hole checks are
  43. // properly optimized away early in Ignition+TurboFan.
  44. /*<replacement>*/
  45. var Buffer = require('safe-buffer').Buffer;
  46. var OurUint8Array = global.Uint8Array || function () {};
  47. function _uint8ArrayToBuffer(chunk) {
  48. return Buffer.from(chunk);
  49. }
  50. function _isUint8Array(obj) {
  51. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  52. }
  53. /*</replacement>*/
  54. /*<replacement>*/
  55. var util = require('core-util-is');
  56. util.inherits = require('inherits');
  57. /*</replacement>*/
  58. /*<replacement>*/
  59. var debugUtil = require('util');
  60. var debug = void 0;
  61. if (debugUtil && debugUtil.debuglog) {
  62. debug = debugUtil.debuglog('stream');
  63. } else {
  64. debug = function () {};
  65. }
  66. /*</replacement>*/
  67. var BufferList = require('./internal/streams/BufferList');
  68. var destroyImpl = require('./internal/streams/destroy');
  69. var StringDecoder;
  70. util.inherits(Readable, Stream);
  71. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  72. function prependListener(emitter, event, fn) {
  73. // Sadly this is not cacheable as some libraries bundle their own
  74. // event emitter implementation with them.
  75. if (typeof emitter.prependListener === 'function') {
  76. return emitter.prependListener(event, fn);
  77. } else {
  78. // This is a hack to make sure that our error handler is attached before any
  79. // userland ones. NEVER DO THIS. This is here only because this code needs
  80. // to continue to work with older versions of Node.js that do not include
  81. // the prependListener() method. The goal is to eventually remove this hack.
  82. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  83. }
  84. }
  85. function ReadableState(options, stream) {
  86. Duplex = Duplex || require('./_stream_duplex');
  87. options = options || {};
  88. // object stream flag. Used to make read(n) ignore n and to
  89. // make all the buffer merging and length checks go away
  90. this.objectMode = !!options.objectMode;
  91. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  92. // the point at which it stops calling _read() to fill the buffer
  93. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  94. var hwm = options.highWaterMark;
  95. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  96. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  97. // cast to ints.
  98. this.highWaterMark = Math.floor(this.highWaterMark);
  99. // A linked list is used to store data chunks instead of an array because the
  100. // linked list can remove elements from the beginning faster than
  101. // array.shift()
  102. this.buffer = new BufferList();
  103. this.length = 0;
  104. this.pipes = null;
  105. this.pipesCount = 0;
  106. this.flowing = null;
  107. this.ended = false;
  108. this.endEmitted = false;
  109. this.reading = false;
  110. // a flag to be able to tell if the event 'readable'/'data' is emitted
  111. // immediately, or on a later tick. We set this to true at first, because
  112. // any actions that shouldn't happen until "later" should generally also
  113. // not happen before the first read call.
  114. this.sync = true;
  115. // whenever we return null, then we set a flag to say
  116. // that we're awaiting a 'readable' event emission.
  117. this.needReadable = false;
  118. this.emittedReadable = false;
  119. this.readableListening = false;
  120. this.resumeScheduled = false;
  121. // has it been destroyed
  122. this.destroyed = false;
  123. // Crypto is kind of old and crusty. Historically, its default string
  124. // encoding is 'binary' so we have to make this configurable.
  125. // Everything else in the universe uses 'utf8', though.
  126. this.defaultEncoding = options.defaultEncoding || 'utf8';
  127. // the number of writers that are awaiting a drain event in .pipe()s
  128. this.awaitDrain = 0;
  129. // if true, a maybeReadMore has been scheduled
  130. this.readingMore = false;
  131. this.decoder = null;
  132. this.encoding = null;
  133. if (options.encoding) {
  134. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  135. this.decoder = new StringDecoder(options.encoding);
  136. this.encoding = options.encoding;
  137. }
  138. }
  139. function Readable(options) {
  140. Duplex = Duplex || require('./_stream_duplex');
  141. if (!(this instanceof Readable)) return new Readable(options);
  142. this._readableState = new ReadableState(options, this);
  143. // legacy
  144. this.readable = true;
  145. if (options) {
  146. if (typeof options.read === 'function') this._read = options.read;
  147. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  148. }
  149. Stream.call(this);
  150. }
  151. Object.defineProperty(Readable.prototype, 'destroyed', {
  152. get: function () {
  153. if (this._readableState === undefined) {
  154. return false;
  155. }
  156. return this._readableState.destroyed;
  157. },
  158. set: function (value) {
  159. // we ignore the value if the stream
  160. // has not been initialized yet
  161. if (!this._readableState) {
  162. return;
  163. }
  164. // backward compatibility, the user is explicitly
  165. // managing destroyed
  166. this._readableState.destroyed = value;
  167. }
  168. });
  169. Readable.prototype.destroy = destroyImpl.destroy;
  170. Readable.prototype._undestroy = destroyImpl.undestroy;
  171. Readable.prototype._destroy = function (err, cb) {
  172. this.push(null);
  173. cb(err);
  174. };
  175. // Manually shove something into the read() buffer.
  176. // This returns true if the highWaterMark has not been hit yet,
  177. // similar to how Writable.write() returns true if you should
  178. // write() some more.
  179. Readable.prototype.push = function (chunk, encoding) {
  180. var state = this._readableState;
  181. var skipChunkCheck;
  182. if (!state.objectMode) {
  183. if (typeof chunk === 'string') {
  184. encoding = encoding || state.defaultEncoding;
  185. if (encoding !== state.encoding) {
  186. chunk = Buffer.from(chunk, encoding);
  187. encoding = '';
  188. }
  189. skipChunkCheck = true;
  190. }
  191. } else {
  192. skipChunkCheck = true;
  193. }
  194. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  195. };
  196. // Unshift should *always* be something directly out of read()
  197. Readable.prototype.unshift = function (chunk) {
  198. return readableAddChunk(this, chunk, null, true, false);
  199. };
  200. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  201. var state = stream._readableState;
  202. if (chunk === null) {
  203. state.reading = false;
  204. onEofChunk(stream, state);
  205. } else {
  206. var er;
  207. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  208. if (er) {
  209. stream.emit('error', er);
  210. } else if (state.objectMode || chunk && chunk.length > 0) {
  211. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  212. chunk = _uint8ArrayToBuffer(chunk);
  213. }
  214. if (addToFront) {
  215. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  216. } else if (state.ended) {
  217. stream.emit('error', new Error('stream.push() after EOF'));
  218. } else {
  219. state.reading = false;
  220. if (state.decoder && !encoding) {
  221. chunk = state.decoder.write(chunk);
  222. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  223. } else {
  224. addChunk(stream, state, chunk, false);
  225. }
  226. }
  227. } else if (!addToFront) {
  228. state.reading = false;
  229. }
  230. }
  231. return needMoreData(state);
  232. }
  233. function addChunk(stream, state, chunk, addToFront) {
  234. if (state.flowing && state.length === 0 && !state.sync) {
  235. stream.emit('data', chunk);
  236. stream.read(0);
  237. } else {
  238. // update the buffer info.
  239. state.length += state.objectMode ? 1 : chunk.length;
  240. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  241. if (state.needReadable) emitReadable(stream);
  242. }
  243. maybeReadMore(stream, state);
  244. }
  245. function chunkInvalid(state, chunk) {
  246. var er;
  247. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  248. er = new TypeError('Invalid non-string/buffer chunk');
  249. }
  250. return er;
  251. }
  252. // if it's past the high water mark, we can push in some more.
  253. // Also, if we have no data yet, we can stand some
  254. // more bytes. This is to work around cases where hwm=0,
  255. // such as the repl. Also, if the push() triggered a
  256. // readable event, and the user called read(largeNumber) such that
  257. // needReadable was set, then we ought to push more, so that another
  258. // 'readable' event will be triggered.
  259. function needMoreData(state) {
  260. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  261. }
  262. Readable.prototype.isPaused = function () {
  263. return this._readableState.flowing === false;
  264. };
  265. // backwards compatibility.
  266. Readable.prototype.setEncoding = function (enc) {
  267. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  268. this._readableState.decoder = new StringDecoder(enc);
  269. this._readableState.encoding = enc;
  270. return this;
  271. };
  272. // Don't raise the hwm > 8MB
  273. var MAX_HWM = 0x800000;
  274. function computeNewHighWaterMark(n) {
  275. if (n >= MAX_HWM) {
  276. n = MAX_HWM;
  277. } else {
  278. // Get the next highest power of 2 to prevent increasing hwm excessively in
  279. // tiny amounts
  280. n--;
  281. n |= n >>> 1;
  282. n |= n >>> 2;
  283. n |= n >>> 4;
  284. n |= n >>> 8;
  285. n |= n >>> 16;
  286. n++;
  287. }
  288. return n;
  289. }
  290. // This function is designed to be inlinable, so please take care when making
  291. // changes to the function body.
  292. function howMuchToRead(n, state) {
  293. if (n <= 0 || state.length === 0 && state.ended) return 0;
  294. if (state.objectMode) return 1;
  295. if (n !== n) {
  296. // Only flow one buffer at a time
  297. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  298. }
  299. // If we're asking for more than the current hwm, then raise the hwm.
  300. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  301. if (n <= state.length) return n;
  302. // Don't have enough
  303. if (!state.ended) {
  304. state.needReadable = true;
  305. return 0;
  306. }
  307. return state.length;
  308. }
  309. // you can override either this method, or the async _read(n) below.
  310. Readable.prototype.read = function (n) {
  311. debug('read', n);
  312. n = parseInt(n, 10);
  313. var state = this._readableState;
  314. var nOrig = n;
  315. if (n !== 0) state.emittedReadable = false;
  316. // if we're doing read(0) to trigger a readable event, but we
  317. // already have a bunch of data in the buffer, then just trigger
  318. // the 'readable' event and move on.
  319. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  320. debug('read: emitReadable', state.length, state.ended);
  321. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  322. return null;
  323. }
  324. n = howMuchToRead(n, state);
  325. // if we've ended, and we're now clear, then finish it up.
  326. if (n === 0 && state.ended) {
  327. if (state.length === 0) endReadable(this);
  328. return null;
  329. }
  330. // All the actual chunk generation logic needs to be
  331. // *below* the call to _read. The reason is that in certain
  332. // synthetic stream cases, such as passthrough streams, _read
  333. // may be a completely synchronous operation which may change
  334. // the state of the read buffer, providing enough data when
  335. // before there was *not* enough.
  336. //
  337. // So, the steps are:
  338. // 1. Figure out what the state of things will be after we do
  339. // a read from the buffer.
  340. //
  341. // 2. If that resulting state will trigger a _read, then call _read.
  342. // Note that this may be asynchronous, or synchronous. Yes, it is
  343. // deeply ugly to write APIs this way, but that still doesn't mean
  344. // that the Readable class should behave improperly, as streams are
  345. // designed to be sync/async agnostic.
  346. // Take note if the _read call is sync or async (ie, if the read call
  347. // has returned yet), so that we know whether or not it's safe to emit
  348. // 'readable' etc.
  349. //
  350. // 3. Actually pull the requested chunks out of the buffer and return.
  351. // if we need a readable event, then we need to do some reading.
  352. var doRead = state.needReadable;
  353. debug('need readable', doRead);
  354. // if we currently have less than the highWaterMark, then also read some
  355. if (state.length === 0 || state.length - n < state.highWaterMark) {
  356. doRead = true;
  357. debug('length less than watermark', doRead);
  358. }
  359. // however, if we've ended, then there's no point, and if we're already
  360. // reading, then it's unnecessary.
  361. if (state.ended || state.reading) {
  362. doRead = false;
  363. debug('reading or ended', doRead);
  364. } else if (doRead) {
  365. debug('do read');
  366. state.reading = true;
  367. state.sync = true;
  368. // if the length is currently zero, then we *need* a readable event.
  369. if (state.length === 0) state.needReadable = true;
  370. // call internal read method
  371. this._read(state.highWaterMark);
  372. state.sync = false;
  373. // If _read pushed data synchronously, then `reading` will be false,
  374. // and we need to re-evaluate how much data we can return to the user.
  375. if (!state.reading) n = howMuchToRead(nOrig, state);
  376. }
  377. var ret;
  378. if (n > 0) ret = fromList(n, state);else ret = null;
  379. if (ret === null) {
  380. state.needReadable = true;
  381. n = 0;
  382. } else {
  383. state.length -= n;
  384. }
  385. if (state.length === 0) {
  386. // If we have nothing in the buffer, then we want to know
  387. // as soon as we *do* get something into the buffer.
  388. if (!state.ended) state.needReadable = true;
  389. // If we tried to read() past the EOF, then emit end on the next tick.
  390. if (nOrig !== n && state.ended) endReadable(this);
  391. }
  392. if (ret !== null) this.emit('data', ret);
  393. return ret;
  394. };
  395. function onEofChunk(stream, state) {
  396. if (state.ended) return;
  397. if (state.decoder) {
  398. var chunk = state.decoder.end();
  399. if (chunk && chunk.length) {
  400. state.buffer.push(chunk);
  401. state.length += state.objectMode ? 1 : chunk.length;
  402. }
  403. }
  404. state.ended = true;
  405. // emit 'readable' now to make sure it gets picked up.
  406. emitReadable(stream);
  407. }
  408. // Don't emit readable right away in sync mode, because this can trigger
  409. // another read() call => stack overflow. This way, it might trigger
  410. // a nextTick recursion warning, but that's not so bad.
  411. function emitReadable(stream) {
  412. var state = stream._readableState;
  413. state.needReadable = false;
  414. if (!state.emittedReadable) {
  415. debug('emitReadable', state.flowing);
  416. state.emittedReadable = true;
  417. if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
  418. }
  419. }
  420. function emitReadable_(stream) {
  421. debug('emit readable');
  422. stream.emit('readable');
  423. flow(stream);
  424. }
  425. // at this point, the user has presumably seen the 'readable' event,
  426. // and called read() to consume some data. that may have triggered
  427. // in turn another _read(n) call, in which case reading = true if
  428. // it's in progress.
  429. // However, if we're not ended, or reading, and the length < hwm,
  430. // then go ahead and try to read some more preemptively.
  431. function maybeReadMore(stream, state) {
  432. if (!state.readingMore) {
  433. state.readingMore = true;
  434. processNextTick(maybeReadMore_, stream, state);
  435. }
  436. }
  437. function maybeReadMore_(stream, state) {
  438. var len = state.length;
  439. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  440. debug('maybeReadMore read 0');
  441. stream.read(0);
  442. if (len === state.length)
  443. // didn't get any data, stop spinning.
  444. break;else len = state.length;
  445. }
  446. state.readingMore = false;
  447. }
  448. // abstract method. to be overridden in specific implementation classes.
  449. // call cb(er, data) where data is <= n in length.
  450. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  451. // arbitrary, and perhaps not very meaningful.
  452. Readable.prototype._read = function (n) {
  453. this.emit('error', new Error('_read() is not implemented'));
  454. };
  455. Readable.prototype.pipe = function (dest, pipeOpts) {
  456. var src = this;
  457. var state = this._readableState;
  458. switch (state.pipesCount) {
  459. case 0:
  460. state.pipes = dest;
  461. break;
  462. case 1:
  463. state.pipes = [state.pipes, dest];
  464. break;
  465. default:
  466. state.pipes.push(dest);
  467. break;
  468. }
  469. state.pipesCount += 1;
  470. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  471. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  472. var endFn = doEnd ? onend : unpipe;
  473. if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
  474. dest.on('unpipe', onunpipe);
  475. function onunpipe(readable, unpipeInfo) {
  476. debug('onunpipe');
  477. if (readable === src) {
  478. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  479. unpipeInfo.hasUnpiped = true;
  480. cleanup();
  481. }
  482. }
  483. }
  484. function onend() {
  485. debug('onend');
  486. dest.end();
  487. }
  488. // when the dest drains, it reduces the awaitDrain counter
  489. // on the source. This would be more elegant with a .once()
  490. // handler in flow(), but adding and removing repeatedly is
  491. // too slow.
  492. var ondrain = pipeOnDrain(src);
  493. dest.on('drain', ondrain);
  494. var cleanedUp = false;
  495. function cleanup() {
  496. debug('cleanup');
  497. // cleanup event handlers once the pipe is broken
  498. dest.removeListener('close', onclose);
  499. dest.removeListener('finish', onfinish);
  500. dest.removeListener('drain', ondrain);
  501. dest.removeListener('error', onerror);
  502. dest.removeListener('unpipe', onunpipe);
  503. src.removeListener('end', onend);
  504. src.removeListener('end', unpipe);
  505. src.removeListener('data', ondata);
  506. cleanedUp = true;
  507. // if the reader is waiting for a drain event from this
  508. // specific writer, then it would cause it to never start
  509. // flowing again.
  510. // So, if this is awaiting a drain, then we just call it now.
  511. // If we don't know, then assume that we are waiting for one.
  512. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  513. }
  514. // If the user pushes more data while we're writing to dest then we'll end up
  515. // in ondata again. However, we only want to increase awaitDrain once because
  516. // dest will only emit one 'drain' event for the multiple writes.
  517. // => Introduce a guard on increasing awaitDrain.
  518. var increasedAwaitDrain = false;
  519. src.on('data', ondata);
  520. function ondata(chunk) {
  521. debug('ondata');
  522. increasedAwaitDrain = false;
  523. var ret = dest.write(chunk);
  524. if (false === ret && !increasedAwaitDrain) {
  525. // If the user unpiped during `dest.write()`, it is possible
  526. // to get stuck in a permanently paused state if that write
  527. // also returned false.
  528. // => Check whether `dest` is still a piping destination.
  529. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  530. debug('false write response, pause', src._readableState.awaitDrain);
  531. src._readableState.awaitDrain++;
  532. increasedAwaitDrain = true;
  533. }
  534. src.pause();
  535. }
  536. }
  537. // if the dest has an error, then stop piping into it.
  538. // however, don't suppress the throwing behavior for this.
  539. function onerror(er) {
  540. debug('onerror', er);
  541. unpipe();
  542. dest.removeListener('error', onerror);
  543. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  544. }
  545. // Make sure our error handler is attached before userland ones.
  546. prependListener(dest, 'error', onerror);
  547. // Both close and finish should trigger unpipe, but only once.
  548. function onclose() {
  549. dest.removeListener('finish', onfinish);
  550. unpipe();
  551. }
  552. dest.once('close', onclose);
  553. function onfinish() {
  554. debug('onfinish');
  555. dest.removeListener('close', onclose);
  556. unpipe();
  557. }
  558. dest.once('finish', onfinish);
  559. function unpipe() {
  560. debug('unpipe');
  561. src.unpipe(dest);
  562. }
  563. // tell the dest that it's being piped to
  564. dest.emit('pipe', src);
  565. // start the flow if it hasn't been started already.
  566. if (!state.flowing) {
  567. debug('pipe resume');
  568. src.resume();
  569. }
  570. return dest;
  571. };
  572. function pipeOnDrain(src) {
  573. return function () {
  574. var state = src._readableState;
  575. debug('pipeOnDrain', state.awaitDrain);
  576. if (state.awaitDrain) state.awaitDrain--;
  577. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  578. state.flowing = true;
  579. flow(src);
  580. }
  581. };
  582. }
  583. Readable.prototype.unpipe = function (dest) {
  584. var state = this._readableState;
  585. var unpipeInfo = { hasUnpiped: false };
  586. // if we're not piping anywhere, then do nothing.
  587. if (state.pipesCount === 0) return this;
  588. // just one destination. most common case.
  589. if (state.pipesCount === 1) {
  590. // passed in one, but it's not the right one.
  591. if (dest && dest !== state.pipes) return this;
  592. if (!dest) dest = state.pipes;
  593. // got a match.
  594. state.pipes = null;
  595. state.pipesCount = 0;
  596. state.flowing = false;
  597. if (dest) dest.emit('unpipe', this, unpipeInfo);
  598. return this;
  599. }
  600. // slow case. multiple pipe destinations.
  601. if (!dest) {
  602. // remove all.
  603. var dests = state.pipes;
  604. var len = state.pipesCount;
  605. state.pipes = null;
  606. state.pipesCount = 0;
  607. state.flowing = false;
  608. for (var i = 0; i < len; i++) {
  609. dests[i].emit('unpipe', this, unpipeInfo);
  610. }return this;
  611. }
  612. // try to find the right one.
  613. var index = indexOf(state.pipes, dest);
  614. if (index === -1) return this;
  615. state.pipes.splice(index, 1);
  616. state.pipesCount -= 1;
  617. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  618. dest.emit('unpipe', this, unpipeInfo);
  619. return this;
  620. };
  621. // set up data events if they are asked for
  622. // Ensure readable listeners eventually get something
  623. Readable.prototype.on = function (ev, fn) {
  624. var res = Stream.prototype.on.call(this, ev, fn);
  625. if (ev === 'data') {
  626. // Start flowing on next tick if stream isn't explicitly paused
  627. if (this._readableState.flowing !== false) this.resume();
  628. } else if (ev === 'readable') {
  629. var state = this._readableState;
  630. if (!state.endEmitted && !state.readableListening) {
  631. state.readableListening = state.needReadable = true;
  632. state.emittedReadable = false;
  633. if (!state.reading) {
  634. processNextTick(nReadingNextTick, this);
  635. } else if (state.length) {
  636. emitReadable(this);
  637. }
  638. }
  639. }
  640. return res;
  641. };
  642. Readable.prototype.addListener = Readable.prototype.on;
  643. function nReadingNextTick(self) {
  644. debug('readable nexttick read 0');
  645. self.read(0);
  646. }
  647. // pause() and resume() are remnants of the legacy readable stream API
  648. // If the user uses them, then switch into old mode.
  649. Readable.prototype.resume = function () {
  650. var state = this._readableState;
  651. if (!state.flowing) {
  652. debug('resume');
  653. state.flowing = true;
  654. resume(this, state);
  655. }
  656. return this;
  657. };
  658. function resume(stream, state) {
  659. if (!state.resumeScheduled) {
  660. state.resumeScheduled = true;
  661. processNextTick(resume_, stream, state);
  662. }
  663. }
  664. function resume_(stream, state) {
  665. if (!state.reading) {
  666. debug('resume read 0');
  667. stream.read(0);
  668. }
  669. state.resumeScheduled = false;
  670. state.awaitDrain = 0;
  671. stream.emit('resume');
  672. flow(stream);
  673. if (state.flowing && !state.reading) stream.read(0);
  674. }
  675. Readable.prototype.pause = function () {
  676. debug('call pause flowing=%j', this._readableState.flowing);
  677. if (false !== this._readableState.flowing) {
  678. debug('pause');
  679. this._readableState.flowing = false;
  680. this.emit('pause');
  681. }
  682. return this;
  683. };
  684. function flow(stream) {
  685. var state = stream._readableState;
  686. debug('flow', state.flowing);
  687. while (state.flowing && stream.read() !== null) {}
  688. }
  689. // wrap an old-style stream as the async data source.
  690. // This is *not* part of the readable stream interface.
  691. // It is an ugly unfortunate mess of history.
  692. Readable.prototype.wrap = function (stream) {
  693. var state = this._readableState;
  694. var paused = false;
  695. var self = this;
  696. stream.on('end', function () {
  697. debug('wrapped end');
  698. if (state.decoder && !state.ended) {
  699. var chunk = state.decoder.end();
  700. if (chunk && chunk.length) self.push(chunk);
  701. }
  702. self.push(null);
  703. });
  704. stream.on('data', function (chunk) {
  705. debug('wrapped data');
  706. if (state.decoder) chunk = state.decoder.write(chunk);
  707. // don't skip over falsy values in objectMode
  708. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  709. var ret = self.push(chunk);
  710. if (!ret) {
  711. paused = true;
  712. stream.pause();
  713. }
  714. });
  715. // proxy all the other methods.
  716. // important when wrapping filters and duplexes.
  717. for (var i in stream) {
  718. if (this[i] === undefined && typeof stream[i] === 'function') {
  719. this[i] = function (method) {
  720. return function () {
  721. return stream[method].apply(stream, arguments);
  722. };
  723. }(i);
  724. }
  725. }
  726. // proxy certain important events.
  727. for (var n = 0; n < kProxyEvents.length; n++) {
  728. stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
  729. }
  730. // when we try to consume some more bytes, simply unpause the
  731. // underlying stream.
  732. self._read = function (n) {
  733. debug('wrapped _read', n);
  734. if (paused) {
  735. paused = false;
  736. stream.resume();
  737. }
  738. };
  739. return self;
  740. };
  741. // exposed for testing purposes only.
  742. Readable._fromList = fromList;
  743. // Pluck off n bytes from an array of buffers.
  744. // Length is the combined lengths of all the buffers in the list.
  745. // This function is designed to be inlinable, so please take care when making
  746. // changes to the function body.
  747. function fromList(n, state) {
  748. // nothing buffered
  749. if (state.length === 0) return null;
  750. var ret;
  751. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  752. // read it all, truncate the list
  753. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
  754. state.buffer.clear();
  755. } else {
  756. // read part of list
  757. ret = fromListPartial(n, state.buffer, state.decoder);
  758. }
  759. return ret;
  760. }
  761. // Extracts only enough buffered data to satisfy the amount requested.
  762. // This function is designed to be inlinable, so please take care when making
  763. // changes to the function body.
  764. function fromListPartial(n, list, hasStrings) {
  765. var ret;
  766. if (n < list.head.data.length) {
  767. // slice is the same for buffers and strings
  768. ret = list.head.data.slice(0, n);
  769. list.head.data = list.head.data.slice(n);
  770. } else if (n === list.head.data.length) {
  771. // first chunk is a perfect match
  772. ret = list.shift();
  773. } else {
  774. // result spans more than one buffer
  775. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  776. }
  777. return ret;
  778. }
  779. // Copies a specified amount of characters from the list of buffered data
  780. // chunks.
  781. // This function is designed to be inlinable, so please take care when making
  782. // changes to the function body.
  783. function copyFromBufferString(n, list) {
  784. var p = list.head;
  785. var c = 1;
  786. var ret = p.data;
  787. n -= ret.length;
  788. while (p = p.next) {
  789. var str = p.data;
  790. var nb = n > str.length ? str.length : n;
  791. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  792. n -= nb;
  793. if (n === 0) {
  794. if (nb === str.length) {
  795. ++c;
  796. if (p.next) list.head = p.next;else list.head = list.tail = null;
  797. } else {
  798. list.head = p;
  799. p.data = str.slice(nb);
  800. }
  801. break;
  802. }
  803. ++c;
  804. }
  805. list.length -= c;
  806. return ret;
  807. }
  808. // Copies a specified amount of bytes from the list of buffered data chunks.
  809. // This function is designed to be inlinable, so please take care when making
  810. // changes to the function body.
  811. function copyFromBuffer(n, list) {
  812. var ret = Buffer.allocUnsafe(n);
  813. var p = list.head;
  814. var c = 1;
  815. p.data.copy(ret);
  816. n -= p.data.length;
  817. while (p = p.next) {
  818. var buf = p.data;
  819. var nb = n > buf.length ? buf.length : n;
  820. buf.copy(ret, ret.length - n, 0, nb);
  821. n -= nb;
  822. if (n === 0) {
  823. if (nb === buf.length) {
  824. ++c;
  825. if (p.next) list.head = p.next;else list.head = list.tail = null;
  826. } else {
  827. list.head = p;
  828. p.data = buf.slice(nb);
  829. }
  830. break;
  831. }
  832. ++c;
  833. }
  834. list.length -= c;
  835. return ret;
  836. }
  837. function endReadable(stream) {
  838. var state = stream._readableState;
  839. // If we get here before consuming all the bytes, then that is a
  840. // bug in node. Should never happen.
  841. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  842. if (!state.endEmitted) {
  843. state.ended = true;
  844. processNextTick(endReadableNT, state, stream);
  845. }
  846. }
  847. function endReadableNT(state, stream) {
  848. // Check that we didn't get one last unshift.
  849. if (!state.endEmitted && state.length === 0) {
  850. state.endEmitted = true;
  851. stream.readable = false;
  852. stream.emit('end');
  853. }
  854. }
  855. function forEach(xs, f) {
  856. for (var i = 0, l = xs.length; i < l; i++) {
  857. f(xs[i], i);
  858. }
  859. }
  860. function indexOf(xs, x) {
  861. for (var i = 0, l = xs.length; i < l; i++) {
  862. if (xs[i] === x) return i;
  863. }
  864. return -1;
  865. }