_stream_transform.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. // a transform stream is a readable/writable stream where you do
  2. // something with the data. Sometimes it's called a "filter",
  3. // but that's not a great name for it, since that implies a thing where
  4. // some bits pass through, and others are simply ignored. (That would
  5. // be a valid example of a transform, of course.)
  6. //
  7. // While the output is causally related to the input, it's not a
  8. // necessarily symmetric or synchronous transformation. For example,
  9. // a zlib stream might take multiple plain-text writes(), and then
  10. // emit a single compressed chunk some time in the future.
  11. //
  12. // Here's how this works:
  13. //
  14. // The Transform stream has all the aspects of the readable and writable
  15. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  16. // internally, and returns false if there's a lot of pending writes
  17. // buffered up. When you call read(), that calls _read(n) until
  18. // there's enough pending readable data buffered up.
  19. //
  20. // In a transform stream, the written data is placed in a buffer. When
  21. // _read(n) is called, it transforms the queued up data, calling the
  22. // buffered _write cb's as it consumes chunks. If consuming a single
  23. // written chunk would result in multiple output chunks, then the first
  24. // outputted bit calls the readcb, and subsequent chunks just go into
  25. // the read buffer, and will cause it to emit 'readable' if necessary.
  26. //
  27. // This way, back-pressure is actually determined by the reading side,
  28. // since _read has to be called to start processing a new chunk. However,
  29. // a pathological inflate type of transform can cause excessive buffering
  30. // here. For example, imagine a stream where every byte of input is
  31. // interpreted as an integer from 0-255, and then results in that many
  32. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  33. // 1kb of data being output. In this case, you could write a very small
  34. // amount of input, and end up with a very large amount of output. In
  35. // such a pathological inflating mechanism, there'd be no way to tell
  36. // the system to stop doing the transform. A single 4MB write could
  37. // cause the system to run out of memory.
  38. //
  39. // However, even in such a pathological case, only a single written chunk
  40. // would be consumed, and then the rest would wait (un-transformed) until
  41. // the results of the previous transformed chunk were consumed.
  42. 'use strict';
  43. module.exports = Transform;
  44. var Duplex = require('./_stream_duplex');
  45. /*<replacement>*/
  46. var util = require('core-util-is');
  47. util.inherits = require('inherits');
  48. /*</replacement>*/
  49. util.inherits(Transform, Duplex);
  50. function TransformState(stream) {
  51. this.afterTransform = function (er, data) {
  52. return afterTransform(stream, er, data);
  53. };
  54. this.needTransform = false;
  55. this.transforming = false;
  56. this.writecb = null;
  57. this.writechunk = null;
  58. this.writeencoding = null;
  59. }
  60. function afterTransform(stream, er, data) {
  61. var ts = stream._transformState;
  62. ts.transforming = false;
  63. var cb = ts.writecb;
  64. if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
  65. ts.writechunk = null;
  66. ts.writecb = null;
  67. if (data !== null && data !== undefined) stream.push(data);
  68. cb(er);
  69. var rs = stream._readableState;
  70. rs.reading = false;
  71. if (rs.needReadable || rs.length < rs.highWaterMark) {
  72. stream._read(rs.highWaterMark);
  73. }
  74. }
  75. function Transform(options) {
  76. if (!(this instanceof Transform)) return new Transform(options);
  77. Duplex.call(this, options);
  78. this._transformState = new TransformState(this);
  79. // when the writable side finishes, then flush out anything remaining.
  80. var stream = this;
  81. // start out asking for a readable event once data is transformed.
  82. this._readableState.needReadable = true;
  83. // we have implemented the _read method, and done the other things
  84. // that Readable wants before the first _read call, so unset the
  85. // sync guard flag.
  86. this._readableState.sync = false;
  87. if (options) {
  88. if (typeof options.transform === 'function') this._transform = options.transform;
  89. if (typeof options.flush === 'function') this._flush = options.flush;
  90. }
  91. this.once('prefinish', function () {
  92. if (typeof this._flush === 'function') this._flush(function (er) {
  93. done(stream, er);
  94. });else done(stream);
  95. });
  96. }
  97. Transform.prototype.push = function (chunk, encoding) {
  98. this._transformState.needTransform = false;
  99. return Duplex.prototype.push.call(this, chunk, encoding);
  100. };
  101. // This is the part where you do stuff!
  102. // override this function in implementation classes.
  103. // 'chunk' is an input chunk.
  104. //
  105. // Call `push(newChunk)` to pass along transformed output
  106. // to the readable side. You may call 'push' zero or more times.
  107. //
  108. // Call `cb(err)` when you are done with this chunk. If you pass
  109. // an error, then that'll put the hurt on the whole operation. If you
  110. // never call cb(), then you'll never get another chunk.
  111. Transform.prototype._transform = function (chunk, encoding, cb) {
  112. throw new Error('Not implemented');
  113. };
  114. Transform.prototype._write = function (chunk, encoding, cb) {
  115. var ts = this._transformState;
  116. ts.writecb = cb;
  117. ts.writechunk = chunk;
  118. ts.writeencoding = encoding;
  119. if (!ts.transforming) {
  120. var rs = this._readableState;
  121. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  122. }
  123. };
  124. // Doesn't matter what the args are here.
  125. // _transform does all the work.
  126. // That we got here means that the readable side wants more data.
  127. Transform.prototype._read = function (n) {
  128. var ts = this._transformState;
  129. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  130. ts.transforming = true;
  131. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  132. } else {
  133. // mark that we need a transform, so that any data that comes in
  134. // will get processed, now that we've asked for it.
  135. ts.needTransform = true;
  136. }
  137. };
  138. function done(stream, er) {
  139. if (er) return stream.emit('error', er);
  140. // if there's nothing in the write buffer, then that means
  141. // that nothing more will ever be provided
  142. var ws = stream._writableState;
  143. var ts = stream._transformState;
  144. if (ws.length) throw new Error('Calling transform done when ws.length != 0');
  145. if (ts.transforming) throw new Error('Calling transform done when still transforming');
  146. return stream.push(null);
  147. }