All files / lib/internal/streams transform.js

95.93% Statements 236/246
85.19% Branches 46/54
100% Functions 6/6
95.93% Lines 236/246

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 24726x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 1632x 1632x 1632x 1631x 1631x 1631x 1631x 1631x 1631x 1631x 1631x 1631x 1631x 1632x 1324x 1324x 1324x 1324x 1324x 1324x 1629x 1629x 1629x 1629x 1629x 1629x 1632x 26x 862x 862x 862x 644x 638x 638x 1x 1x 1x     1x 1x 637x 638x 2x 2x 637x 637x 69x 69x 644x 644x 4x 4x 4x 3x 3x 3x 2x 2x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x     3x 3x 4x     4x 862x 218x 218x 213x 213x 218x 862x 26x 861x 861x 577x 577x 861x 26x 26x 26x 26x 1x 26x 26x 26x 125841x 125841x 125841x 125841x 125841x 125841x 125823x 125823x 4x 4x 4x 125819x 125819x 118726x 118726x 125819x 125819x 125819x 125823x 125823x 22x 125823x 125797x 125823x 22x 22x 125841x 125841x 3x 3x 3x 3x 3x 3x 2x 2x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 2x     3x 3x 1x 3x 3x 3x     3x 26x 26x 26x 2050x 14x 14x 14x 14x 26x  
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// a transform stream is a readable/writable stream where you do
// something with the data.  Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored.  (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation.  For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes.  When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up.  When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer.  When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks.  If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk.  However,
// a pathological inflate type of transform can cause excessive buffering
// here.  For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output.  In this case, you could write a very small
// amount of input, and end up with a very large amount of output.  In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform.  A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
 
'use strict';
 
const {
  ObjectSetPrototypeOf,
  Symbol
} = primordials;
 
module.exports = Transform;
const {
  ERR_METHOD_NOT_IMPLEMENTED
} = require('internal/errors').codes;
const Duplex = require('internal/streams/duplex');
ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype);
ObjectSetPrototypeOf(Transform, Duplex);
 
const kCallback = Symbol('kCallback');
 
function Transform(options) {
  if (!(this instanceof Transform))
    return new Transform(options);
 
  Duplex.call(this, options);
 
  // We have implemented the _read method, and done the other things
  // that Readable wants before the first _read call, so unset the
  // sync guard flag.
  this._readableState.sync = false;
 
  this[kCallback] = null;
 
  if (options) {
    if (typeof options.transform === 'function')
      this._transform = options.transform;
 
    if (typeof options.flush === 'function')
      this._flush = options.flush;
  }
 
  // When the writable side finishes, then flush out anything remaining.
  // Backwards compat. Some Transform streams incorrectly implement _final
  // instead of or in addition to _flush. By using 'prefinish' instead of
  // implementing _final we continue supporting this unfortunate use case.
  this.on('prefinish', prefinish);
}
 
function final(cb) {
  let called = false;
  if (typeof this._flush === 'function' && !this.destroyed) {
    const result = this._flush((er, data) => {
      called = true;
      if (er) {
        if (cb) {
          cb(er);
        } else {
          this.destroy(er);
        }
        return;
      }
 
      if (data != null) {
        this.push(data);
      }
      this.push(null);
      if (cb) {
        cb();
      }
    });
    if (result !== undefined && result !== null) {
      try {
        const then = result.then;
        if (typeof then === 'function') {
          then.call(
            result,
            (data) => {
              if (called)
                return;
              if (data != null)
                this.push(data);
              this.push(null);
              if (cb)
                process.nextTick(cb);
            },
            (err) => {
              if (cb) {
                process.nextTick(cb, err);
              } else {
                process.nextTick(() => this.destroy(err));
              }
            });
        }
      } catch (err) {
        process.nextTick(() => this.destroy(err));
      }
    }
  } else {
    this.push(null);
    if (cb) {
      cb();
    }
  }
}
 
function prefinish() {
  if (this._final !== final) {
    final.call(this);
  }
}
 
Transform.prototype._final = final;
 
Transform.prototype._transform = function(chunk, encoding, callback) {
  throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()');
};
 
Transform.prototype._write = function(chunk, encoding, callback) {
  const rState = this._readableState;
  const wState = this._writableState;
  const length = rState.length;
 
  let called = false;
  const result = this._transform(chunk, encoding, (err, val) => {
    called = true;
    if (err) {
      callback(err);
      return;
    }
 
    if (val != null) {
      this.push(val);
    }
 
    if (
      wState.ended || // Backwards compat.
      length === rState.length || // Backwards compat.
      rState.length < rState.highWaterMark ||
      rState.length === 0
    ) {
      callback();
    } else {
      this[kCallback] = callback;
    }
  });
  if (result !== undefined && result != null) {
    try {
      const then = result.then;
      if (typeof then === 'function') {
        then.call(
          result,
          (val) => {
            if (called)
              return;
 
            if (val != null) {
              this.push(val);
            }
 
            if (
              wState.ended ||
              length === rState.length ||
              rState.length < rState.highWaterMark ||
              rState.length === 0) {
              process.nextTick(callback);
            } else {
              this[kCallback] = callback;
            }
          },
          (err) => {
            process.nextTick(callback, err);
          });
      }
    } catch (err) {
      process.nextTick(callback, err);
    }
  }
};
 
Transform.prototype._read = function() {
  if (this[kCallback]) {
    const callback = this[kCallback];
    this[kCallback] = null;
    callback();
  }
};