Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_stream_readable.js 28KB

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