function destroyStream()

in lib/apm-client/http-apm-client/index.js [1779:1815]


function destroyStream(stream) {
  if (
    stream instanceof zlib.Gzip ||
    stream instanceof zlib.Gunzip ||
    stream instanceof zlib.Deflate ||
    stream instanceof zlib.DeflateRaw ||
    stream instanceof zlib.Inflate ||
    stream instanceof zlib.InflateRaw ||
    stream instanceof zlib.Unzip
  ) {
    // Zlib streams doesn't have a destroy function in Node.js 6. On top of
    // that simply calling destroy on a zlib stream in Node.js 8+ will result
    // in a memory leak as the handle isn't closed (an operation normally done
    // by calling close). So until that is fixed, we need to manually close the
    // handle after destroying the stream.
    //
    // PR: https://github.com/nodejs/node/pull/23734
    if (typeof stream.destroy === 'function') {
      // Manually close the stream instead of calling `close()` as that would
      // have emitted 'close' again when calling `destroy()`
      if (stream._handle && typeof stream._handle.close === 'function') {
        stream._handle.close();
        stream._handle = null;
      }

      stream.destroy();
    } else if (typeof stream.close === 'function') {
      stream.close();
    }
  } else {
    // For other streams we assume calling destroy is enough
    if (typeof stream.destroy === 'function') stream.destroy();
    // Or if there's no destroy (which Node.js 6 will not have on regular
    // streams), emit `close` as that should trigger almost the same effect
    else if (typeof stream.emit === 'function') stream.emit('close');
  }
}