3 [![NPM Version][npm-version-image]][npm-url]
4 [![NPM Downloads][npm-downloads-image]][npm-url]
5 [![Node.js Version][node-version-image]][node-version-url]
6 [![Build Status][travis-image]][travis-url]
7 [![Test Coverage][coveralls-image]][coveralls-url]
9 Execute a listener when a response is about to write headers.
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):
18 $ npm install on-headers
23 <!-- eslint-disable no-unused-vars -->
26 var onHeaders = require('on-headers')
29 ### onHeaders(res, listener)
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.
35 When this is called multiple times on the same `res`, the `listener`s are fired
36 in the reverse order they were added.
41 var http = require('http')
42 var onHeaders = require('on-headers')
45 .createServer(onRequest)
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')
55 function onRequest (req, res) {
56 onHeaders(res, addPoweredBy)
58 res.setHeader('Content-Type', 'text/plain')
73 [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/on-headers/master
74 [coveralls-url]: https://coveralls.io/r/jshttp/on-headers?branch=master
75 [node-version-image]: https://badgen.net/npm/node/on-headers
76 [node-version-url]: https://nodejs.org/en/download
77 [npm-downloads-image]: https://badgen.net/npm/dm/on-headers
78 [npm-url]: https://npmjs.org/package/on-headers
79 [npm-version-image]: https://badgen.net/npm/v/on-headers
80 [travis-image]: https://badgen.net/travis/jshttp/on-headers/master
81 [travis-url]: https://travis-ci.org/jshttp/on-headers