Skip to content

Instantly share code, notes, and snippets.

@cyco130
Created February 22, 2023 16:25
Show Gist options
  • Save cyco130/1db447d8c07843c5234452ff49b97589 to your computer and use it in GitHub Desktop.
Save cyco130/1db447d8c07843c5234452ff49b97589 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