Skip to content

Instantly share code, notes, and snippets.

@alxgrk
Created January 17, 2024 23:03
Show Gist options
  • Save alxgrk/92e982672a17aa7dd7aed987f6906ed8 to your computer and use it in GitHub Desktop.
Save alxgrk/92e982672a17aa7dd7aed987f6906ed8 to your computer and use it in GitHub Desktop.
AbortController in Express.js
const express = require("express");
const app = express();
console.log("initializing")
app.get("/foo", (req, res) => {
const abort = new AbortController()
console.log("entered /foo")
req.on('end', () => {
// this is only called when the request successfully sent a response
console.log("ended");
});
req.on('close', () => {
// this is called everytime the request ends - no matter
// whether a response was sent successfully or not
abort.abort();
console.log("closed");
});
const timeout = setTimeout(() => {
console.log("Completed")
res.sendStatus(200);
}, 2000);
abort.signal.onabort = () => {
// this clears the timeout, so if the client cancels the request within
// the 2 seconds of `setTimeout`, `Completed` will not be printed
console.log("aborted")
clearTimeout(timeout);
};
});
app.listen(3000)
@alxgrk
Copy link
Author

alxgrk commented Jan 17, 2024

Usage: $ node express-abort.js

Sequence of log output:

initializing

# successful request
entered /foo
Completed
ended
aborted
closed

# request cancelled by client
entered /foo
aborted
closed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment