pax_global_header00006660000000000000000000000064142052052770014516gustar00rootroot0000000000000052 comment=1111fe8e913debaf3da9bd4f6bda216ef36097fa on-finished-2.4.1/000077500000000000000000000000001420520527700137255ustar00rootroot00000000000000on-finished-2.4.1/.eslintignore000066400000000000000000000000261420520527700164260ustar00rootroot00000000000000coverage node_modules on-finished-2.4.1/.eslintrc.yml000066400000000000000000000002321420520527700163460ustar00rootroot00000000000000root: true extends: - standard - plugin:markdown/recommended plugins: - markdown overrides: - files: '**/*.md' processor: 'markdown/markdown' on-finished-2.4.1/.github/000077500000000000000000000000001420520527700152655ustar00rootroot00000000000000on-finished-2.4.1/.github/workflows/000077500000000000000000000000001420520527700173225ustar00rootroot00000000000000on-finished-2.4.1/.github/workflows/ci.yml000066400000000000000000000126251420520527700204460ustar00rootroot00000000000000name: ci on: - pull_request - push jobs: test: runs-on: ubuntu-latest strategy: matrix: name: - Node.js 0.8 - Node.js 0.10 - Node.js 0.12 - io.js 1.x - io.js 2.x - io.js 3.x - Node.js 4.x - Node.js 5.x - Node.js 6.x - Node.js 7.x - Node.js 8.0 # test early async_hooks - Node.js 8.x - Node.js 10.x - Node.js 11.x - Node.js 12.x - Node.js 13.x - Node.js 14.x - Node.js 15.x - Node.js 16.x - Node.js 17.x include: - name: Node.js 0.8 node-version: "0.8" npm-i: mocha@2.5.3 npm-rm: nyc - name: Node.js 0.10 node-version: "0.10" npm-i: mocha@3.5.3 nyc@10.3.2 - name: Node.js 0.12 node-version: "0.12" npm-i: mocha@3.5.3 nyc@10.3.2 - name: io.js 1.x node-version: "1.8" npm-i: mocha@3.5.3 nyc@10.3.2 - name: io.js 2.x node-version: "2.5" npm-i: mocha@3.5.3 nyc@10.3.2 - name: io.js 3.x node-version: "3.3" npm-i: mocha@3.5.3 nyc@10.3.2 - name: Node.js 4.x node-version: "4.9" npm-i: mocha@5.2.0 nyc@11.9.0 - name: Node.js 5.x node-version: "5.12" npm-i: mocha@5.2.0 nyc@11.9.0 - name: Node.js 6.x node-version: "6.17" npm-i: mocha@6.2.2 nyc@14.1.1 - name: Node.js 7.x node-version: "7.10" npm-i: mocha@6.2.2 nyc@14.1.1 - name: Node.js 8.0 node-version: "8.0" npm-i: mocha@6.2.2 nyc@14.1.1 - name: Node.js 8.x node-version: "8.17" npm-i: mocha@7.2.0 - name: Node.js 10.x node-version: "10.24" npm-i: mocha@8.4.0 - name: Node.js 11.x node-version: "11.15" - name: Node.js 12.x node-version: "12.22" - name: Node.js 13.x node-version: "13.14" - name: Node.js 14.x node-version: "14.19" - name: Node.js 15.x node-version: "15.14" - name: Node.js 16.x node-version: "16.14" - name: Node.js 17.x node-version: "17.5" steps: - uses: actions/checkout@v2 - name: Install Node.js ${{ matrix.node-version }} shell: bash -eo pipefail -l {0} run: | nvm install --default ${{ matrix.node-version }} if [[ "${{ matrix.node-version }}" == 0.* && "$(cut -d. -f2 <<< "${{ matrix.node-version }}")" -lt 10 ]]; then nvm install --alias=npm 0.10 nvm use ${{ matrix.node-version }} sed -i '1s;^.*$;'"$(printf '#!%q' "$(nvm which npm)")"';' "$(readlink -f "$(which npm)")" npm config set strict-ssl false fi dirname "$(nvm which ${{ matrix.node-version }})" >> "$GITHUB_PATH" - name: Configure npm run: npm config set shrinkwrap false - name: Remove npm module(s) ${{ matrix.npm-rm }} run: npm rm --silent --save-dev ${{ matrix.npm-rm }} if: matrix.npm-rm != '' - name: Install npm module(s) ${{ matrix.npm-i }} run: npm install --save-dev ${{ matrix.npm-i }} if: matrix.npm-i != '' - name: Setup Node.js version-specific dependencies shell: bash run: | # eslint for linting # - remove on Node.js < 10 if [[ "$(cut -d. -f1 <<< "${{ matrix.node-version }}")" -lt 10 ]]; then node -pe 'Object.keys(require("./package").devDependencies).join("\n")' | \ grep -E '^eslint(-|$)' | \ sort -r | \ xargs -n1 npm rm --silent --save-dev fi - name: Install Node.js dependencies run: npm install - name: List environment id: list_env shell: bash run: | echo "node@$(node -v)" echo "npm@$(npm -v)" npm -s ls ||: (npm -s ls --depth=0 ||:) | awk -F'[ @]' 'NR>1 && $2 { print "::set-output name=" $2 "::" $3 }' - name: Run tests shell: bash run: | if npm -ps ls nyc | grep -q nyc; then npm run test-ci cp coverage/lcov.info "coverage/${{ matrix.name }}.lcov" else npm test fi - name: Lint code if: steps.list_env.outputs.eslint != '' run: npm run lint - name: Collect code coverage if: steps.list_env.outputs.nyc != '' run: | if [[ -d ./coverage ]]; then mv ./coverage "./${{ matrix.name }}" mkdir ./coverage mv "./${{ matrix.name }}" "./coverage/${{ matrix.name }}" fi - name: Upload code coverage uses: actions/upload-artifact@v2 if: steps.list_env.outputs.nyc != '' with: name: coverage path: ./coverage retention-days: 1 coverage: needs: test runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install lcov shell: bash run: sudo apt-get -y install lcov - name: Collect coverage reports uses: actions/download-artifact@v2 with: name: coverage path: ./coverage - name: Merge coverage reports shell: bash run: find ./coverage -name lcov.info -exec printf '-a %q\n' {} \; | xargs lcov -o ./coverage/lcov.info - name: Upload coverage report uses: coverallsapp/github-action@master with: github-token: ${{ secrets.GITHUB_TOKEN }} on-finished-2.4.1/.gitignore000066400000000000000000000001021420520527700157060ustar00rootroot00000000000000.nyc_output coverage node_modules npm-debug.log package-lock.json on-finished-2.4.1/HISTORY.md000066400000000000000000000035111420520527700154100ustar00rootroot000000000000002.4.1 / 2022-02-22 ================== * Fix error on early async hooks implementations 2.4.0 / 2022-02-21 ================== * Prevent loss of async hooks context 2.3.0 / 2015-05-26 ================== * Add defined behavior for HTTP `CONNECT` requests * Add defined behavior for HTTP `Upgrade` requests * deps: ee-first@1.1.1 2.2.1 / 2015-04-22 ================== * Fix `isFinished(req)` when data buffered 2.2.0 / 2014-12-22 ================== * Add message object to callback arguments 2.1.1 / 2014-10-22 ================== * Fix handling of pipelined requests 2.1.0 / 2014-08-16 ================== * Check if `socket` is detached * Return `undefined` for `isFinished` if state unknown 2.0.0 / 2014-08-16 ================== * Add `isFinished` function * Move to `jshttp` organization * Remove support for plain socket argument * Rename to `on-finished` * Support both `req` and `res` as arguments * deps: ee-first@1.0.5 1.2.2 / 2014-06-10 ================== * Reduce listeners added to emitters - avoids "event emitter leak" warnings when used multiple times on same request 1.2.1 / 2014-06-08 ================== * Fix returned value when already finished 1.2.0 / 2014-06-05 ================== * Call callback when called on already-finished socket 1.1.4 / 2014-05-27 ================== * Support node.js 0.8 1.1.3 / 2014-04-30 ================== * Make sure errors passed as instanceof `Error` 1.1.2 / 2014-04-18 ================== * Default the `socket` to passed-in object 1.1.1 / 2014-01-16 ================== * Rename module to `finished` 1.1.0 / 2013-12-25 ================== * Call callback when called on already-errored socket 1.0.1 / 2013-12-20 ================== * Actually pass the error to the callback 1.0.0 / 2013-12-20 ================== * Initial release on-finished-2.4.1/LICENSE000066400000000000000000000022171420520527700147340ustar00rootroot00000000000000(The MIT License) Copyright (c) 2013 Jonathan Ong Copyright (c) 2014 Douglas Christopher Wilson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. on-finished-2.4.1/README.md000066400000000000000000000120501420520527700152020ustar00rootroot00000000000000# on-finished [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-image]][node-url] [![Build Status][ci-image]][ci-url] [![Coverage Status][coveralls-image]][coveralls-url] Execute a callback when a HTTP request closes, finishes, or errors. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install on-finished ``` ## API ```js var onFinished = require('on-finished') ``` ### onFinished(res, listener) Attach a listener to listen for the response to finish. The listener will be invoked only once when the response finished. If the response finished to an error, the first argument will contain the error. If the response has already finished, the listener will be invoked. Listening to the end of a response would be used to close things associated with the response, like open files. Listener is invoked as `listener(err, res)`. ```js onFinished(res, function (err, res) { // clean up open fds, etc. // err contains the error if request error'd }) ``` ### onFinished(req, listener) Attach a listener to listen for the request to finish. The listener will be invoked only once when the request finished. If the request finished to an error, the first argument will contain the error. If the request has already finished, the listener will be invoked. Listening to the end of a request would be used to know when to continue after reading the data. Listener is invoked as `listener(err, req)`. ```js var data = '' req.setEncoding('utf8') req.on('data', function (str) { data += str }) onFinished(req, function (err, req) { // data is read unless there is err }) ``` ### onFinished.isFinished(res) Determine if `res` is already finished. This would be useful to check and not even start certain operations if the response has already finished. ### onFinished.isFinished(req) Determine if `req` is already finished. This would be useful to check and not even start certain operations if the request has already finished. ## Special Node.js requests ### HTTP CONNECT method The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: > The CONNECT method requests that the recipient establish a tunnel to > the destination origin server identified by the request-target and, > if successful, thereafter restrict its behavior to blind forwarding > of packets, in both directions, until the tunnel is closed. Tunnels > are commonly used to create an end-to-end virtual connection, through > one or more proxies, which can then be secured using TLS (Transport > Layer Security, [RFC5246]). In Node.js, these request objects come from the `'connect'` event on the HTTP server. When this module is used on a HTTP `CONNECT` request, the request is considered "finished" immediately, **due to limitations in the Node.js interface**. This means if the `CONNECT` request contains a request entity, the request will be considered "finished" even before it has been read. There is no such thing as a response object to a `CONNECT` request in Node.js, so there is no support for one. ### HTTP Upgrade request The meaning of the `Upgrade` header from RFC 7230, section 6.1: > The "Upgrade" header field is intended to provide a simple mechanism > for transitioning from HTTP/1.1 to some other protocol on the same > connection. In Node.js, these request objects come from the `'upgrade'` event on the HTTP server. When this module is used on a HTTP request with an `Upgrade` header, the request is considered "finished" immediately, **due to limitations in the Node.js interface**. This means if the `Upgrade` request contains a request entity, the request will be considered "finished" even before it has been read. There is no such thing as a response object to a `Upgrade` request in Node.js, so there is no support for one. ## Example The following code ensures that file descriptors are always closed once the response finishes. ```js var destroy = require('destroy') var fs = require('fs') var http = require('http') var onFinished = require('on-finished') http.createServer(function onRequest (req, res) { var stream = fs.createReadStream('package.json') stream.pipe(res) onFinished(res, function () { destroy(stream) }) }) ``` ## License [MIT](LICENSE) [ci-image]: https://badgen.net/github/checks/jshttp/on-finished/master?label=ci [ci-url]: https://github.com/jshttp/on-finished/actions/workflows/ci.yml [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/on-finished/master [coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master [node-image]: https://badgen.net/npm/node/on-finished [node-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/on-finished [npm-url]: https://npmjs.org/package/on-finished [npm-version-image]: https://badgen.net/npm/v/on-finished on-finished-2.4.1/index.js000066400000000000000000000105161420520527700153750ustar00rootroot00000000000000/*! * on-finished * Copyright(c) 2013 Jonathan Ong * Copyright(c) 2014 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module exports. * @public */ module.exports = onFinished module.exports.isFinished = isFinished /** * Module dependencies. * @private */ var asyncHooks = tryRequireAsyncHooks() var first = require('ee-first') /** * Variables. * @private */ /* istanbul ignore next */ var defer = typeof setImmediate === 'function' ? setImmediate : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } /** * Invoke callback when the response has finished, useful for * cleaning up resources afterwards. * * @param {object} msg * @param {function} listener * @return {object} * @public */ function onFinished (msg, listener) { if (isFinished(msg) !== false) { defer(listener, null, msg) return msg } // attach the listener to the message attachListener(msg, wrap(listener)) return msg } /** * Determine if message is already finished. * * @param {object} msg * @return {boolean} * @public */ function isFinished (msg) { var socket = msg.socket if (typeof msg.finished === 'boolean') { // OutgoingMessage return Boolean(msg.finished || (socket && !socket.writable)) } if (typeof msg.complete === 'boolean') { // IncomingMessage return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) } // don't know return undefined } /** * Attach a finished listener to the message. * * @param {object} msg * @param {function} callback * @private */ function attachFinishedListener (msg, callback) { var eeMsg var eeSocket var finished = false function onFinish (error) { eeMsg.cancel() eeSocket.cancel() finished = true callback(error) } // finished on first message event eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) function onSocket (socket) { // remove listener msg.removeListener('socket', onSocket) if (finished) return if (eeMsg !== eeSocket) return // finished on first socket event eeSocket = first([[socket, 'error', 'close']], onFinish) } if (msg.socket) { // socket already assigned onSocket(msg.socket) return } // wait for socket to be assigned msg.on('socket', onSocket) if (msg.socket === undefined) { // istanbul ignore next: node.js 0.8 patch patchAssignSocket(msg, onSocket) } } /** * Attach the listener to the message. * * @param {object} msg * @return {function} * @private */ function attachListener (msg, listener) { var attached = msg.__onFinished // create a private single listener with queue if (!attached || !attached.queue) { attached = msg.__onFinished = createListener(msg) attachFinishedListener(msg, attached) } attached.queue.push(listener) } /** * Create listener on message. * * @param {object} msg * @return {function} * @private */ function createListener (msg) { function listener (err) { if (msg.__onFinished === listener) msg.__onFinished = null if (!listener.queue) return var queue = listener.queue listener.queue = null for (var i = 0; i < queue.length; i++) { queue[i](err, msg) } } listener.queue = [] return listener } /** * Patch ServerResponse.prototype.assignSocket for node.js 0.8. * * @param {ServerResponse} res * @param {function} callback * @private */ // istanbul ignore next: node.js 0.8 patch function patchAssignSocket (res, callback) { var assignSocket = res.assignSocket if (typeof assignSocket !== 'function') return // res.on('socket', callback) is broken in 0.8 res.assignSocket = function _assignSocket (socket) { assignSocket.call(this, socket) callback(socket) } } /** * Try to require async_hooks * @private */ function tryRequireAsyncHooks () { try { return require('async_hooks') } catch (e) { return {} } } /** * Wrap function with async resource, if possible. * AsyncResource.bind static method backported. * @private */ function wrap (fn) { var res // create anonymous resource if (asyncHooks.AsyncResource) { res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn') } // incompatible node.js if (!res || !res.runInAsyncScope) { return fn } // return bound function return res.runInAsyncScope.bind(res, fn, null) } on-finished-2.4.1/package.json000066400000000000000000000020411420520527700162100ustar00rootroot00000000000000{ "name": "on-finished", "description": "Execute a callback when a request closes, finishes, or errors", "version": "2.4.1", "contributors": [ "Douglas Christopher Wilson ", "Jonathan Ong (http://jongleberry.com)" ], "license": "MIT", "repository": "jshttp/on-finished", "dependencies": { "ee-first": "1.1.1" }, "devDependencies": { "eslint": "7.32.0", "eslint-config-standard": "14.1.1", "eslint-plugin-import": "2.25.4", "eslint-plugin-markdown": "2.2.1", "eslint-plugin-node": "11.1.0", "eslint-plugin-promise": "5.2.0", "eslint-plugin-standard": "4.1.0", "mocha": "9.2.1", "nyc": "15.1.0" }, "engines": { "node": ">= 0.8" }, "files": [ "HISTORY.md", "LICENSE", "index.js" ], "scripts": { "lint": "eslint .", "test": "mocha --reporter spec --bail --check-leaks test/", "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", "test-cov": "nyc --reporter=html --reporter=text npm test" } } on-finished-2.4.1/test/000077500000000000000000000000001420520527700147045ustar00rootroot00000000000000on-finished-2.4.1/test/.eslintrc.yml000066400000000000000000000000231420520527700173230ustar00rootroot00000000000000env: mocha: true on-finished-2.4.1/test/test.js000066400000000000000000000755121420520527700162330ustar00rootroot00000000000000 var assert = require('assert') var asyncHooks = tryRequire('async_hooks') var http = require('http') var net = require('net') var onFinished = require('..') var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function' ? describe : describe.skip describe('onFinished(res, listener)', function () { it('should invoke listener given an unknown object', function (done) { onFinished({}, done) }) describe('when the response finishes', function () { it('should fire the callback', function (done) { var server = http.createServer(function (req, res) { onFinished(res, done) setTimeout(res.end.bind(res), 0) }) sendGet(server) }) it('should include the response object', function (done) { var server = http.createServer(function (req, res) { onFinished(res, function (err, msg) { assert.ok(!err) assert.strictEqual(msg, res) done() }) setTimeout(res.end.bind(res), 0) }) sendGet(server) }) describe('when called after finish', function () { it('should fire when called after finish', function (done) { var server = http.createServer(function (req, res) { onFinished(res, function () { onFinished(res, done) }) setTimeout(res.end.bind(res), 0) }) sendGet(server) }) describeAsyncHooks('when async local storage', function () { it('should presist store in callback', function (done) { var asyncLocalStorage = new asyncHooks.AsyncLocalStorage() var store = { foo: 'bar' } var server = http.createServer(function (req, res) { onFinished(res, function () { asyncLocalStorage.run(store, function () { onFinished(res, function () { assert.strictEqual(asyncLocalStorage.getStore().foo, 'bar') done() }) }) }) setTimeout(res.end.bind(res), 0) }) sendGet(server) }) }) }) describeAsyncHooks('when async local storage', function () { it('should presist store in callback', function (done) { var asyncLocalStorage = new asyncHooks.AsyncLocalStorage() var store = { foo: 'bar' } var server = http.createServer(function (req, res) { asyncLocalStorage.run(store, function () { onFinished(res, function () { assert.strictEqual(asyncLocalStorage.getStore().foo, 'bar') done() }) }) setTimeout(res.end.bind(res), 0) }) sendGet(server) }) }) }) describe('when using keep-alive', function () { it('should fire for each response', function (done) { var called = false var server = http.createServer(function (req, res) { onFinished(res, function () { if (called) { socket.end() server.close() done(called !== req ? null : new Error('fired twice on same req')) return } called = req writeRequest(socket) }) res.end() }) var socket server.listen(function () { socket = net.connect(this.address().port, function () { writeRequest(this) }) }) }) }) describe('when requests pipelined', function () { it('should fire for each request', function (done) { var count = 0 var responses = [] var server = http.createServer(function (req, res) { responses.push(res) onFinished(res, function (err) { assert.ifError(err) assert.strictEqual(responses[0], res) responses.shift() if (responses.length === 0) { socket.end() return } responses[0].end('response b') }) onFinished(req, function (err) { assert.ifError(err) if (++count !== 2) { return } assert.strictEqual(responses.length, 2) responses[0].end('response a') }) if (responses.length === 1) { // second request writeRequest(socket) } req.resume() }) var socket server.listen(function () { var data = '' socket = net.connect(this.address().port, function () { writeRequest(this) }) socket.on('data', function (chunk) { data += chunk.toString('binary') }) socket.on('end', function () { assert.ok(/response a/.test(data)) assert.ok(/response b/.test(data)) server.close(done) }) }) }) }) describe('when response errors', function () { it('should fire with error', function (done) { var server = http.createServer(function (req, res) { onFinished(res, function (err) { assert.ok(err) server.close(done) }) socket.on('error', noop) socket.write('W') }) var socket server.listen(function () { socket = net.connect(this.address().port, function () { writeRequest(this, true) }) }) }) it('should include the response object', function (done) { var server = http.createServer(function (req, res) { onFinished(res, function (err, msg) { assert.ok(err) assert.strictEqual(msg, res) server.close(done) }) socket.on('error', noop) socket.write('W') }) var socket server.listen(function () { socket = net.connect(this.address().port, function () { writeRequest(this, true) }) }) }) }) describe('when the response aborts', function () { it('should execute the callback', function (done) { var client var server = http.createServer(function (req, res) { onFinished(res, close(server, done)) setTimeout(client.abort.bind(client), 0) }) server.listen(function () { var port = this.address().port client = http.get('http://127.0.0.1:' + port) client.on('error', noop) }) }) }) describe('when calling many times on same response', function () { it('should not print warnings', function (done) { var server = http.createServer(function (req, res) { var stderr = captureStderr(function () { for (var i = 0; i < 400; i++) { onFinished(res, noop) } }) onFinished(res, done) assert.strictEqual(stderr, '') res.end() }) server.listen(function () { var port = this.address().port http.get('http://127.0.0.1:' + port, function (res) { res.resume() res.on('end', server.close.bind(server)) }) }) }) }) }) describe('isFinished(res)', function () { it('should return undefined for unknown object', function () { assert.strictEqual(onFinished.isFinished({}), undefined) }) it('should be false before response finishes', function (done) { var server = http.createServer(function (req, res) { assert.ok(!onFinished.isFinished(res)) res.end() done() }) sendGet(server) }) it('should be true after response finishes', function (done) { var server = http.createServer(function (req, res) { onFinished(res, function (err) { assert.ifError(err) assert.ok(onFinished.isFinished(res)) done() }) res.end() }) sendGet(server) }) describe('when requests pipelined', function () { it('should have correct state when socket shared', function (done) { var count = 0 var responses = [] var server = http.createServer(function (req, res) { responses.push(res) onFinished(req, function (err) { assert.ifError(err) if (++count !== 2) { return } assert.ok(!onFinished.isFinished(responses[0])) assert.ok(!onFinished.isFinished(responses[1])) responses[0].end() responses[1].end() socket.end() server.close(done) }) if (responses.length === 1) { // second request writeRequest(socket) } req.resume() }) var socket server.listen(function () { socket = net.connect(this.address().port, function () { writeRequest(this) }) }) }) it('should handle aborted requests', function (done) { var count = 0 var requests = 0 var server = http.createServer(function (req, res) { requests++ onFinished(req, function (err) { switch (++count) { case 1: assert.ifError(err) // abort the socket socket.on('error', noop) socket.destroy() break case 2: server.close(done) break } }) req.resume() if (requests === 1) { // second request writeRequest(socket, true) } }) var socket server.listen(function () { socket = net.connect(this.address().port, function () { writeRequest(this) }) }) }) }) describe('when response errors', function () { it('should return true', function (done) { var server = http.createServer(function (req, res) { onFinished(res, function (err) { assert.ok(err) assert.ok(onFinished.isFinished(res)) server.close(done) }) socket.on('error', noop) socket.write('W') }) var socket server.listen(function () { socket = net.connect(this.address().port, function () { writeRequest(this, true) }) }) }) }) describe('when the response aborts', function () { it('should return true', function (done) { var client var server = http.createServer(function (req, res) { onFinished(res, function (err) { assert.ifError(err) assert.ok(onFinished.isFinished(res)) server.close(done) }) setTimeout(client.abort.bind(client), 0) }) server.listen(function () { var port = this.address().port client = http.get('http://127.0.0.1:' + port) client.on('error', noop) }) }) }) }) describe('onFinished(req, listener)', function () { describe('when the request finishes', function () { it('should fire the callback', function (done) { var server = http.createServer(function (req, res) { onFinished(req, done) req.resume() setTimeout(res.end.bind(res), 0) }) sendGet(server) }) it('should include the request object', function (done) { var server = http.createServer(function (req, res) { onFinished(req, function (err, msg) { assert.ok(!err) assert.strictEqual(msg, req) done() }) req.resume() setTimeout(res.end.bind(res), 0) }) sendGet(server) }) describe('when called after finish', function () { it('should fire when called after finish', function (done) { var server = http.createServer(function (req, res) { onFinished(req, function () { onFinished(req, done) }) req.resume() setTimeout(res.end.bind(res), 0) }) sendGet(server) }) describeAsyncHooks('when async local storage', function () { it('should presist store in callback', function (done) { var asyncLocalStorage = new asyncHooks.AsyncLocalStorage() var store = { foo: 'bar' } var server = http.createServer(function (req, res) { onFinished(req, function () { asyncLocalStorage.run(store, function () { onFinished(req, function () { assert.strictEqual(asyncLocalStorage.getStore().foo, 'bar') done() }) }) }) req.resume() setTimeout(res.end.bind(res), 0) }) sendGet(server) }) }) }) describeAsyncHooks('when async local storage', function () { it('should presist store in callback', function (done) { var asyncLocalStorage = new asyncHooks.AsyncLocalStorage() var store = { foo: 'bar' } var server = http.createServer(function (req, res) { asyncLocalStorage.run(store, function () { onFinished(req, function () { assert.strictEqual(asyncLocalStorage.getStore().foo, 'bar') done() }) }) req.resume() setTimeout(res.end.bind(res), 0) }) sendGet(server) }) }) }) describe('when using keep-alive', function () { it('should fire for each request', function (done) { var called = false var server = http.createServer(function (req, res) { var data = '' onFinished(req, function (err) { assert.ifError(err) assert.strictEqual(data, 'A') if (called) { socket.end() server.close() done(called !== req ? null : new Error('fired twice on same req')) return } called = req res.end() writeRequest(socket, true) }) req.setEncoding('utf8') req.on('data', function (str) { data += str }) socket.write('1\r\nA\r\n') socket.write('0\r\n\r\n') }) var socket server.listen(function () { socket = net.connect(this.address().port, function () { writeRequest(this, true) }) }) }) }) describe('when request errors', function () { it('should fire with error', function (done) { var server = http.createServer(function (req, res) { onFinished(req, function (err) { assert.ok(err) server.close(done) }) socket.on('error', noop) socket.write('W') }) var socket server.listen(function () { socket = net.connect(this.address().port, function () { writeRequest(this, true) }) }) }) it('should include the request object', function (done) { var server = http.createServer(function (req, res) { onFinished(req, function (err, msg) { assert.ok(err) assert.strictEqual(msg, req) server.close(done) }) socket.on('error', noop) socket.write('W') }) var socket server.listen(function () { socket = net.connect(this.address().port, function () { writeRequest(this, true) }) }) }) }) describe('when requests pipelined', function () { it('should handle socket errors', function (done) { var count = 0 var server = http.createServer(function (req) { var num = ++count onFinished(req, function (err) { assert.ok(err) if (!--wait) server.close(done) }) if (num === 1) { // second request writeRequest(socket, true) req.pause() } else { // cause framing error in second request socket.write('W') req.resume() } }) var socket var wait = 3 server.listen(function () { socket = net.connect(this.address().port, function () { writeRequest(this) }) socket.on('close', function () { assert.strictEqual(count, 2) if (!--wait) server.close(done) }) socket.resume() }) }) }) describe('when the request aborts', function () { it('should execute the callback', function (done) { var client var server = http.createServer(function (req, res) { onFinished(req, close(server, done)) setTimeout(client.abort.bind(client), 0) }) server.listen(function () { var port = this.address().port client = http.get('http://127.0.0.1:' + port) client.on('error', noop) }) }) }) describe('when calling many times on same request', function () { it('should not print warnings', function (done) { var server = http.createServer(function (req, res) { var stderr = captureStderr(function () { for (var i = 0; i < 400; i++) { onFinished(req, noop) } }) onFinished(req, done) assert.strictEqual(stderr, '') res.end() }) server.listen(function () { var port = this.address().port http.get('http://127.0.0.1:' + port, function (res) { res.resume() res.on('end', server.close.bind(server)) }) }) }) }) describe('when CONNECT method', function () { it('should fire when request finishes', function (done) { var client var server = http.createServer(function (req, res) { res.statusCode = 405 res.end() }) server.on('connect', function (req, socket, bodyHead) { var data = [bodyHead] onFinished(req, function (err) { assert.ifError(err) assert.strictEqual(Buffer.concat(data).toString(), 'knock, knock') socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'ping') socket.end('pong') }) socket.write('HTTP/1.1 200 OK\r\n\r\n') }) req.on('data', function (chunk) { data.push(chunk) }) }) server.listen(function () { client = http.request({ hostname: '127.0.0.1', method: 'CONNECT', path: '127.0.0.1:80', port: this.address().port }) client.on('connect', function (res, socket, bodyHead) { socket.write('ping') socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'pong') socket.end() server.close(done) }) }) client.end('knock, knock') }) }) it('should fire when called after finish', function (done) { var client var server = http.createServer(function (req, res) { res.statusCode = 405 res.end() }) server.on('connect', function (req, socket, bodyHead) { var data = [bodyHead] onFinished(req, function (err) { assert.ifError(err) assert.strictEqual(Buffer.concat(data).toString(), 'knock, knock') socket.write('HTTP/1.1 200 OK\r\n\r\n') }) socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'ping') onFinished(req, function () { socket.end('pong') }) }) req.on('data', function (chunk) { data.push(chunk) }) }) server.listen(function () { client = http.request({ hostname: '127.0.0.1', method: 'CONNECT', path: '127.0.0.1:80', port: this.address().port }) client.on('connect', function (res, socket, bodyHead) { socket.write('ping') socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'pong') socket.end() server.close(done) }) }) client.end('knock, knock') }) }) }) describe('when Upgrade request', function () { it('should fire when request finishes', function (done) { var client var server = http.createServer(function (req, res) { res.statusCode = 405 res.end() }) server.on('upgrade', function (req, socket, bodyHead) { var data = [bodyHead] onFinished(req, function (err) { assert.ifError(err) assert.strictEqual(Buffer.concat(data).toString(), 'knock, knock') socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'ping') socket.end('pong') }) socket.write('HTTP/1.1 101 Switching Protocols\r\n') socket.write('Connection: Upgrade\r\n') socket.write('Upgrade: Raw\r\n') socket.write('\r\n') }) req.on('data', function (chunk) { data.push(chunk) }) }) server.listen(function () { client = http.request({ headers: { Connection: 'Upgrade', Upgrade: 'Raw' }, hostname: '127.0.0.1', port: this.address().port }) client.on('upgrade', function (res, socket, bodyHead) { socket.write('ping') socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'pong') socket.end() server.close(done) }) }) client.end('knock, knock') }) }) it('should fire when called after finish', function (done) { var client var server = http.createServer(function (req, res) { res.statusCode = 405 res.end() }) server.on('upgrade', function (req, socket, bodyHead) { var data = [bodyHead] onFinished(req, function (err) { assert.ifError(err) assert.strictEqual(Buffer.concat(data).toString(), 'knock, knock') socket.write('HTTP/1.1 101 Switching Protocols\r\n') socket.write('Connection: Upgrade\r\n') socket.write('Upgrade: Raw\r\n') socket.write('\r\n') }) socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'ping') onFinished(req, function () { socket.end('pong') }) }) req.on('data', function (chunk) { data.push(chunk) }) }) server.listen(function () { client = http.request({ headers: { Connection: 'Upgrade', Upgrade: 'Raw' }, hostname: '127.0.0.1', port: this.address().port }) client.on('upgrade', function (res, socket, bodyHead) { socket.write('ping') socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'pong') socket.end() server.close(done) }) }) client.end('knock, knock') }) }) }) }) describe('isFinished(req)', function () { it('should return undefined for unknown object', function () { assert.strictEqual(onFinished.isFinished({}), undefined) }) it('should be false before request finishes', function (done) { var server = http.createServer(function (req, res) { assert.ok(!onFinished.isFinished(req)) req.resume() res.end() done() }) sendGet(server) }) it('should be true after request finishes', function (done) { var server = http.createServer(function (req, res) { onFinished(req, function (err) { assert.ifError(err) assert.ok(onFinished.isFinished(req)) done() }) req.resume() res.end() }) sendGet(server) }) describe('when request data buffered', function () { it('should be false before request finishes', function (done) { var server = http.createServer(function (req, res) { assert.ok(!onFinished.isFinished(req)) req.pause() setTimeout(function () { assert.ok(!onFinished.isFinished(req)) req.resume() res.end() done() }, 10) }) sendGet(server) }) }) describe('when request errors', function () { it('should return true', function (done) { var server = http.createServer(function (req, res) { onFinished(req, function (err) { assert.ok(err) assert.ok(onFinished.isFinished(req)) server.close(done) }) socket.on('error', noop) socket.write('W') }) var socket server.listen(function () { socket = net.connect(this.address().port, function () { writeRequest(this, true) }) }) }) }) describe('when the request aborts', function () { it('should return true', function (done) { var client var server = http.createServer(function (req, res) { onFinished(res, function (err) { assert.ifError(err) assert.ok(onFinished.isFinished(req)) server.close(done) }) setTimeout(client.abort.bind(client), 0) }) server.listen(function () { var port = this.address().port client = http.get('http://127.0.0.1:' + port) client.on('error', noop) }) }) }) describe('when CONNECT method', function () { it('should be true immediately', function (done) { var client var server = http.createServer(function (req, res) { res.statusCode = 405 res.end() }) server.on('connect', function (req, socket, bodyHead) { assert.ok(onFinished.isFinished(req)) assert.strictEqual(bodyHead.length, 0) req.resume() socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'ping') socket.end('pong') }) socket.write('HTTP/1.1 200 OK\r\n\r\n') }) server.listen(function () { client = http.request({ hostname: '127.0.0.1', method: 'CONNECT', path: '127.0.0.1:80', port: this.address().port }) client.on('connect', function (res, socket, bodyHead) { socket.write('ping') socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'pong') socket.end() server.close(done) }) }) client.end() }) }) it('should be true after request finishes', function (done) { var client var server = http.createServer(function (req, res) { res.statusCode = 405 res.end() }) server.on('connect', function (req, socket, bodyHead) { var data = [bodyHead] onFinished(req, function (err) { assert.ifError(err) assert.ok(onFinished.isFinished(req)) assert.strictEqual(Buffer.concat(data).toString(), 'knock, knock') socket.write('HTTP/1.1 200 OK\r\n\r\n') }) socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'ping') socket.end('pong') }) req.on('data', function (chunk) { data.push(chunk) }) }) server.listen(function () { client = http.request({ hostname: '127.0.0.1', method: 'CONNECT', path: '127.0.0.1:80', port: this.address().port }) client.on('connect', function (res, socket, bodyHead) { socket.write('ping') socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'pong') socket.end() server.close(done) }) }) client.end('knock, knock') }) }) }) describe('when Upgrade request', function () { it('should be true immediately', function (done) { var client var server = http.createServer(function (req, res) { res.statusCode = 405 res.end() }) server.on('upgrade', function (req, socket, bodyHead) { assert.ok(onFinished.isFinished(req)) assert.strictEqual(bodyHead.length, 0) req.resume() socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'ping') socket.end('pong') }) socket.write('HTTP/1.1 101 Switching Protocols\r\n') socket.write('Connection: Upgrade\r\n') socket.write('Upgrade: Raw\r\n') socket.write('\r\n') }) server.listen(function () { client = http.request({ headers: { Connection: 'Upgrade', Upgrade: 'Raw' }, hostname: '127.0.0.1', port: this.address().port }) client.on('upgrade', function (res, socket, bodyHead) { socket.write('ping') socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'pong') socket.end() server.close(done) }) }) client.end() }) }) it('should be true after request finishes', function (done) { var client var server = http.createServer(function (req, res) { res.statusCode = 405 res.end() }) server.on('upgrade', function (req, socket, bodyHead) { var data = [bodyHead] onFinished(req, function (err) { assert.ifError(err) assert.ok(onFinished.isFinished(req)) assert.strictEqual(Buffer.concat(data).toString(), 'knock, knock') socket.write('HTTP/1.1 101 Switching Protocols\r\n') socket.write('Connection: Upgrade\r\n') socket.write('Upgrade: Raw\r\n') socket.write('\r\n') }) socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'ping') socket.end('pong') }) req.on('data', function (chunk) { data.push(chunk) }) }) server.listen(function () { client = http.request({ headers: { Connection: 'Upgrade', Upgrade: 'Raw' }, hostname: '127.0.0.1', port: this.address().port }) client.on('upgrade', function (res, socket, bodyHead) { socket.write('ping') socket.on('data', function (chunk) { assert.strictEqual(chunk.toString(), 'pong') socket.end() server.close(done) }) }) client.end('knock, knock') }) }) }) }) function captureStderr (fn) { var chunks = [] var write = process.stderr.write process.stderr.write = function write (chunk, encoding) { chunks.push(new Buffer(chunk, encoding)) // eslint-disable-line node/no-deprecated-api } try { fn() } finally { process.stderr.write = write } return Buffer.concat(chunks).toString('utf8') } function close (server, callback) { return function (error) { server.close(function (err) { callback(error || err) }) } } function noop () {} function sendGet (server) { server.listen(function onListening () { var port = this.address().port http.get('http://127.0.0.1:' + port, function onResponse (res) { res.resume() res.on('end', server.close.bind(server)) }) }) } function tryRequire (name) { try { return require(name) } catch (e) { return {} } } function writeRequest (socket, chunked) { socket.write('GET / HTTP/1.1\r\n') socket.write('Host: localhost\r\n') socket.write('Connection: keep-alive\r\n') if (chunked) { socket.write('Transfer-Encoding: chunked\r\n') } socket.write('\r\n') }