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.

81 lines
2.1 KiB

  1. # on-headers
  2. [![NPM Version][npm-version-image]][npm-url]
  3. [![NPM Downloads][npm-downloads-image]][npm-url]
  4. [![Node.js Version][node-version-image]][node-version-url]
  5. [![Build Status][travis-image]][travis-url]
  6. [![Test Coverage][coveralls-image]][coveralls-url]
  7. Execute a listener when a response is about to write headers.
  8. ## Installation
  9. This is a [Node.js](https://nodejs.org/en/) module available through the
  10. [npm registry](https://www.npmjs.com/). Installation is done using the
  11. [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
  12. ```sh
  13. $ npm install on-headers
  14. ```
  15. ## API
  16. <!-- eslint-disable no-unused-vars -->
  17. ```js
  18. var onHeaders = require('on-headers')
  19. ```
  20. ### onHeaders(res, listener)
  21. This will add the listener `listener` to fire when headers are emitted for `res`.
  22. The listener is passed the `response` object as it's context (`this`). Headers are
  23. considered to be emitted only once, right before they are sent to the client.
  24. When this is called multiple times on the same `res`, the `listener`s are fired
  25. in the reverse order they were added.
  26. ## Examples
  27. ```js
  28. var http = require('http')
  29. var onHeaders = require('on-headers')
  30. http
  31. .createServer(onRequest)
  32. .listen(3000)
  33. function addPoweredBy () {
  34. // set if not set by end of request
  35. if (!this.getHeader('X-Powered-By')) {
  36. this.setHeader('X-Powered-By', 'Node.js')
  37. }
  38. }
  39. function onRequest (req, res) {
  40. onHeaders(res, addPoweredBy)
  41. res.setHeader('Content-Type', 'text/plain')
  42. res.end('hello!')
  43. }
  44. ```
  45. ## Testing
  46. ```sh
  47. $ npm test
  48. ```
  49. ## License
  50. [MIT](LICENSE)
  51. [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/on-headers/master
  52. [coveralls-url]: https://coveralls.io/r/jshttp/on-headers?branch=master
  53. [node-version-image]: https://badgen.net/npm/node/on-headers
  54. [node-version-url]: https://nodejs.org/en/download
  55. [npm-downloads-image]: https://badgen.net/npm/dm/on-headers
  56. [npm-url]: https://npmjs.org/package/on-headers
  57. [npm-version-image]: https://badgen.net/npm/v/on-headers
  58. [travis-image]: https://badgen.net/travis/jshttp/on-headers/master
  59. [travis-url]: https://travis-ci.org/jshttp/on-headers