index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. // We define these manually to ensure they're always copied
  3. // even if they would move up the prototype chain
  4. // https://nodejs.org/api/http.html#http_class_http_incomingmessage
  5. const knownProperties = [
  6. 'aborted',
  7. 'complete',
  8. 'headers',
  9. 'httpVersion',
  10. 'httpVersionMinor',
  11. 'httpVersionMajor',
  12. 'method',
  13. 'rawHeaders',
  14. 'rawTrailers',
  15. 'setTimeout',
  16. 'socket',
  17. 'statusCode',
  18. 'statusMessage',
  19. 'trailers',
  20. 'url'
  21. ];
  22. module.exports = (fromStream, toStream) => {
  23. if (toStream._readableState.autoDestroy) {
  24. throw new Error('The second stream must have the `autoDestroy` option set to `false`');
  25. }
  26. const fromProperties = new Set(Object.keys(fromStream).concat(knownProperties));
  27. const properties = {};
  28. for (const property of fromProperties) {
  29. // Don't overwrite existing properties.
  30. if (property in toStream) {
  31. continue;
  32. }
  33. properties[property] = {
  34. get() {
  35. const value = fromStream[property];
  36. const isFunction = typeof value === 'function';
  37. return isFunction ? value.bind(fromStream) : value;
  38. },
  39. set(value) {
  40. fromStream[property] = value;
  41. },
  42. enumerable: true,
  43. configurable: false
  44. };
  45. }
  46. Object.defineProperties(toStream, properties);
  47. fromStream.once('aborted', () => {
  48. toStream.destroy();
  49. toStream.emit('aborted');
  50. });
  51. fromStream.once('close', () => {
  52. if (fromStream.complete) {
  53. if (toStream.readable) {
  54. toStream.once('end', () => {
  55. toStream.emit('close');
  56. });
  57. } else {
  58. toStream.emit('close');
  59. }
  60. } else {
  61. toStream.emit('close');
  62. }
  63. });
  64. return toStream;
  65. };