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.

index.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*!
  2. * on-headers
  3. * Copyright(c) 2014 Douglas Christopher Wilson
  4. * MIT Licensed
  5. */
  6. 'use strict'
  7. /**
  8. * Reference to Array slice.
  9. */
  10. var slice = Array.prototype.slice
  11. /**
  12. * Execute a listener when a response is about to write headers.
  13. *
  14. * @param {Object} res
  15. * @return {Function} listener
  16. * @api public
  17. */
  18. module.exports = function onHeaders(res, listener) {
  19. if (!res) {
  20. throw new TypeError('argument res is required')
  21. }
  22. if (typeof listener !== 'function') {
  23. throw new TypeError('argument listener must be a function')
  24. }
  25. res.writeHead = createWriteHead(res.writeHead, listener)
  26. }
  27. function createWriteHead(prevWriteHead, listener) {
  28. var fired = false;
  29. // return function with core name and argument list
  30. return function writeHead(statusCode) {
  31. // set headers from arguments
  32. var args = setWriteHeadHeaders.apply(this, arguments);
  33. // fire listener
  34. if (!fired) {
  35. fired = true
  36. listener.call(this)
  37. // pass-along an updated status code
  38. if (typeof args[0] === 'number' && this.statusCode !== args[0]) {
  39. args[0] = this.statusCode
  40. args.length = 1
  41. }
  42. }
  43. prevWriteHead.apply(this, args);
  44. }
  45. }
  46. function setWriteHeadHeaders(statusCode) {
  47. var length = arguments.length
  48. var headerIndex = length > 1 && typeof arguments[1] === 'string'
  49. ? 2
  50. : 1
  51. var headers = length >= headerIndex + 1
  52. ? arguments[headerIndex]
  53. : undefined
  54. this.statusCode = statusCode
  55. // the following block is from node.js core
  56. if (Array.isArray(headers)) {
  57. // handle array case
  58. for (var i = 0, len = headers.length; i < len; ++i) {
  59. this.setHeader(headers[i][0], headers[i][1])
  60. }
  61. } else if (headers) {
  62. // handle object case
  63. var keys = Object.keys(headers)
  64. for (var i = 0; i < keys.length; i++) {
  65. var k = keys[i]
  66. if (k) this.setHeader(k, headers[k])
  67. }
  68. }
  69. // copy leading arguments
  70. var args = new Array(Math.min(length, headerIndex))
  71. for (var i = 0; i < args.length; i++) {
  72. args[i] = arguments[i]
  73. }
  74. return args
  75. }