_stream_readable.js 26 KB

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