arnaucode 112745d6fa | 8 years ago | |
---|---|---|
.. | ||
HISTORY.md | 8 years ago | |
LICENSE | 8 years ago | |
README.md | 8 years ago | |
index.js | 8 years ago | |
package.json | 8 years ago |
Execute a callback when a request closes, finishes, or errors.
$ npm install on-finished
var onFinished = require('on-finished')
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.
onFinished(res, function (err) {
// clean up open fds, etc.
})
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.
var data = ''
req.setEncoding('utf8')
res.on('data', function (str) {
data += str
})
onFinished(req, function (err) {
// data is read unless there is err
})
Determine if res
is already finished. This would be useful to check and
not even start certain operations if the response has already finished.
Determine if req
is already finished. This would be useful to check and
not even start certain operations if the request has already finished.
The following code ensures that file descriptors are always closed once the response finishes.
var destroy = require('destroy')
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 (err) {
destroy(stream)
})
})