/usr/lib/nodejs/on-finished/index.js is in node-on-finished 2.1.0-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | /*!
* 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
}
|