_stream_readable.js 25 KB

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