Skip to content

Instantly share code, notes, and snippets.

@FredKSchott
Forked from cyco130/als.mjs
Created February 22, 2023 22:03
Show Gist options
  • Save FredKSchott/664ddb23fde1b0b9172edb75ff42f1a5 to your computer and use it in GitHub Desktop.
Save FredKSchott/664ddb23fde1b0b9172edb75ff42f1a5 to your computer and use it in GitHub Desktop.
AsyncLocalStorage-based Node server framework
import { createServer } from "node:http";
import { AsyncLocalStorage } from "node:async_hooks";
const asyncLocalStorage = new AsyncLocalStorage();
createServer((req, res) => {
asyncLocalStorage.run({ req, res }, () => {
asyncHandler().catch((err) => {
console.error(err);
if (!res.writableEnded) {
res.statusCode = 500;
res.end("Internal Server Error");
}
});
});
}).listen(3000, () => {
console.log("Server listening on http://localhost:3000");
});
// Define global request and response objects
Object.defineProperty(global, "request", {
get() {
return asyncLocalStorage.getStore().req;
},
});
Object.defineProperty(global, "response", {
get() {
return asyncLocalStorage.getStore().res;
},
});
async function asyncHandler() {
// Do something async
await new Promise((resolve) => setTimeout(resolve, 1000));
// Use global request and response as you see fit
response.end(`${request.method} ${request.url}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment