-
-
Save FredKSchott/664ddb23fde1b0b9172edb75ff42f1a5 to your computer and use it in GitHub Desktop.
AsyncLocalStorage-based Node server framework
This file contains hidden or 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
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