Created
March 30, 2023 22:59
-
-
Save krukid/5698ee72f4a5165945715f1d79b82397 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const app = express(); | |
const port = 3000; | |
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); | |
app.use((req, res, next) => { | |
const handler = (event, ...args) => { | |
console.log(`got ${event} (${req.res?.destroyed})`, args); | |
// handle only the first event that comes in | |
// for (const k in handlers) { | |
// res.removeListener(k, handlers[k]); | |
// } | |
// console.log(`cleaned up and done ${event}`); | |
}; | |
const handlers = { | |
close: handler.bind(null, 'close'), | |
finish: handler.bind(null, 'finish'), | |
error: handler.bind(null, 'error'), | |
}; | |
res.once('close', handlers.close); | |
res.once('finish', handlers.finish); | |
res.once('error', handlers.error); | |
// next(err) does not trigger res "error" | |
next(); | |
}) | |
app.get('/', async (req, res) => { | |
console.log('=> GET /'); | |
await sleep(5000); | |
// does not trigger res "error" | |
// throw new Error('qdwqdw'); | |
// does not trigger res "error" (but res.socket "error" - yes) | |
// res.destroy(new Error('dqdwwqd')); | |
console.log('<= GET /'); | |
res.status(200).json({ ok: true }); | |
}) | |
app.listen(port, '0.0.0.0', () => { | |
console.log(`listening on ${port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment