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