pax_global_header00006660000000000000000000000064123740113200014503gustar00rootroot0000000000000052 comment=1ad808e704e2aeda3a7464b78cacead2fb453727 on-finished-2.1.0/000077500000000000000000000000001237401132000137065ustar00rootroot00000000000000on-finished-2.1.0/.gitignore000066400000000000000000000000441237401132000156740ustar00rootroot00000000000000coverage node_modules npm-debug.log on-finished-2.1.0/.travis.yml000066400000000000000000000004321237401132000160160ustar00rootroot00000000000000language: node_js node_js: - "0.8" - "0.10" - "0.11" matrix: allow_failures: - node_js: "0.11" fast_finish: true script: "npm run-script test-travis" after_script: "test $TRAVIS_NODE_VERSION = '0.10' && npm install coveralls@2 && cat ./coverage/lcov.info | coveralls" on-finished-2.1.0/HISTORY.md000066400000000000000000000023721237401132000153750ustar00rootroot000000000000002.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.1.0/LICENSE000066400000000000000000000022171237401132000147150ustar00rootroot00000000000000(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.1.0/README.md000066400000000000000000000045411237401132000151710ustar00rootroot00000000000000# on-finished [![NPM Version](http://img.shields.io/npm/v/on-finished.svg?style=flat)](https://www.npmjs.org/package/on-finished) [![Node.js Version](http://img.shields.io/badge/node.js->=_0.8-brightgreen.svg?style=flat)](http://nodejs.org/download/) [![Build Status](http://img.shields.io/travis/jshttp/on-finished.svg?style=flat)](https://travis-ci.org/jshttp/on-finished) [![Coverage Status](https://img.shields.io/coveralls/jshttp/on-finished.svg?style=flat)](https://coveralls.io/r/jshttp/on-finished) Execute a callback when a request closes, finishes, or errors. ## Install ```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 to an error, the first argument will contain the error. Listening to the end of a response would be used to close things associated with the response, like open files. ```js onFinished(res, function (err) { // clean up open fds, etc. }) ``` ### 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 to an error, the first argument will contain the error. Listening to the end of a request would be used to know when to continue after reading the data. ```js var data = '' req.setEncoding('utf8') res.on('data', function (str) { data += str }) onFinished(req, function (err) { // 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. ### Example The following code ensures that file descriptors are always closed once the response finishes. ```js var destroy = require('destroy') var http = require('http') var onFinished = require('finished') http.createServer(function onRequest(req, res) { var stream = fs.createReadStream('package.json') stream.pipe(res) onFinished(res, function (err) { destroy(stream) }) }) ``` ## License [MIT](LICENSE) on-finished-2.1.0/index.js000066400000000000000000000043711237401132000153600ustar00rootroot00000000000000/*! * on-finished * Copyright(c) 2013 Jonathan Ong * Copyright(c) 2014 Douglas Christopher Wilson * MIT Licensed */ /** * Module exports. */ module.exports = onFinished; module.exports.isFinished = isFinished; /** * Module dependencies. */ var first = require('ee-first') /** * Variables. */ /* 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} * @api public */ function onFinished(msg, listener) { if (isFinished(msg) !== false) { defer(listener) return msg } // attach the listener to the message attachListener(msg, listener) return msg } /** * Determine is message is already finished. * * @param {object} msg * @return {boolean} * @api public */ function isFinished(msg) { var socket = msg.socket if (typeof msg.finished === 'boolean') { // OutgoingMessage return Boolean(!socket || msg.finished || !socket.writable) } if (typeof msg.complete === 'boolean') { // IncomingMessage return Boolean(!socket || msg.complete || !socket.readable) } // don't know return undefined } /** * Attach the listener to the message. * * @param {object} msg * @return {function} * @api private */ function attachListener(msg, listener) { var attached = msg.__onFinished var socket = msg.socket // create a private single listener with queue if (!attached || !attached.queue) { attached = msg.__onFinished = createListener(msg) // finished on first event first([ [socket, 'error', 'close'], [msg, 'end', 'finish'], ], attached) } attached.queue.push(listener) } /** * Create listener on message. * * @param {object} msg * @return {function} * @api 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) } } listener.queue = [] return listener } on-finished-2.1.0/package.json000066400000000000000000000015611237401132000161770ustar00rootroot00000000000000{ "name": "on-finished", "description": "Execute a callback when a request closes, finishes, or errors", "version": "2.1.0", "contributors": [ "Douglas Christopher Wilson ", "Jonathan Ong (http://jongleberry.com)" ], "license": "MIT", "repository": "jshttp/on-finished", "dependencies": { "ee-first": "1.0.5" }, "devDependencies": { "istanbul": "0.3.0", "mocha": "~1.21.4" }, "engine": { "node": ">= 0.8.0" }, "files": [ "HISTORY.md", "LICENSE", "index.js" ], "scripts": { "test": "mocha --reporter spec --bail --check-leaks test/", "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" } } on-finished-2.1.0/test/000077500000000000000000000000001237401132000146655ustar00rootroot00000000000000on-finished-2.1.0/test/test.js000066400000000000000000000254711237401132000162130ustar00rootroot00000000000000 var assert = require('assert') var http = require('http') var net = require('net') var onFinished = require('..') describe('onFinished(res, listener)', function () { it('should invoke listener given an unknwon 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 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) }) }) 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 response errors', function () { it('should fire with error', function (done) { var server = http.createServer(function (req, res) { onFinished(res, function (err) { assert.ok(err) 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, 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.equal(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('close', 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 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)) 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)) 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 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) }) }) 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.equal(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) 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 execute the callback', function (done) { var client var server = http.createServer(function (req, res) { onFinished(req, 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.equal(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('close', server.close.bind(server)) }) }) }) }) }) describe('isFinished(req)', function () { it('should invoke listener given an unknwon object', function (done) { onFinished({}, done) }) 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 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)) 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)) 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) }) }) }) }) function captureStderr(fn) { var chunks = [] var write = process.stderr.write process.stderr.write = function write(chunk, encoding) { chunks.push(new Buffer(chunk, encoding)) } try { fn() } finally { process.stderr.write = write } return Buffer.concat(chunks).toString('utf8') } 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('close', server.close.bind(server)) }) }) } 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') }