Skip to content

refactor: use stream.finished() instead of custom implementation #56

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 44 additions & 54 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,8 @@ module.exports.isFinished = isFinished
* @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)) }
const asyncHooks = tryRequireAsyncHooks()
const stream = require('stream')

/**
* Invoke callback when the response has finished, useful for
Expand All @@ -45,7 +35,7 @@ var defer = typeof setImmediate === 'function'

function onFinished (msg, listener) {
if (isFinished(msg) !== false) {
defer(listener, null, msg)
setImmediate(listener, null, msg)
return msg
}
Comment on lines 37 to 40
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The if block can be removed if we only accept Streams. There is a test with an unknown object blocking this change:

 it('should invoke listener given an unknown object', function (done) {
    onFinished({}, done)
  })


Expand Down Expand Up @@ -89,57 +79,78 @@ function isFinished (msg) {
*/

function attachFinishedListener (msg, callback) {
var eeMsg
var eeSocket
var finished = false
let finished = false
let cleanupSocket

function onFinish (error) {
eeMsg.cancel()
eeSocket.cancel()

if (finished) return
finished = true
callback(error)
}

// finished on first message event
eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish)
const cleanupFinished = stream.finished(msg, (error) => {
cleanupFinished()
if (cleanupSocket) {
cleanupSocket()
}

// ignore premature close error
if (error && error.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
onFinish(error)
} else {
onFinish()
}
})

function onSocket (socket) {
// remove listener
msg.removeListener('socket', onSocket)

if (finished) return
if (eeMsg !== eeSocket) return

function onSocketErrorOrClose (error) {
// remove listeners
socket.removeListener('error', onSocketErrorOrClose)
socket.removeListener('close', onSocketErrorOrClose)

onFinish(error)
}

// finished on first socket event
eeSocket = first([[socket, 'error', 'close']], onFinish)
socket.on('error', onSocketErrorOrClose)
socket.on('close', onSocketErrorOrClose)

// cleanup socket listeners
cleanupSocket = function () {
socket.removeListener('error', onSocketErrorOrClose)
socket.removeListener('close', onSocketErrorOrClose)
}
}

if (msg.socket) {
// socket already assigned
onSocket(msg.socket)
return
}
} else {
// wait for socket to be assigned
msg.on('socket', onSocket)

// 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)
// cleanup socket listener in case the socket is never assigned
cleanupSocket = function () {
msg.removeListener('socket', onSocket)
}
}
}

/**
* Attach the listener to the message.
*
* @param {object} msg
* @return {function}
* @param {function} listener
* @private
*/

function attachListener (msg, listener) {
var attached = msg.__onFinished
let attached = msg.__onFinished

// create a private single listener with queue
if (!attached || !attached.queue) {
Expand Down Expand Up @@ -176,27 +187,6 @@ function createListener (msg) {
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
Expand Down
5 changes: 1 addition & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@
],
"license": "MIT",
"repository": "jshttp/on-finished",
"dependencies": {
"ee-first": "1.1.1"
},
"devDependencies": {
"eslint": "8.17.0",
"eslint-config-standard": "14.1.1",
Expand All @@ -32,7 +29,7 @@
],
"scripts": {
"lint": "eslint .",
"test": "mocha --reporter spec --bail --check-leaks test/",
"test": "mocha --reporter spec --check-leaks test/",
"test-ci": "nyc --reporter=lcovonly --reporter=text npm test",
"test-cov": "nyc --reporter=html --reporter=text npm test"
}
Expand Down