Skip to content

Instantly share code, notes, and snippets.

@matthewoestreich
Created November 17, 2020 22:04
Show Gist options
  • Save matthewoestreich/a7302d7c9e7e610524ed68c339c5e2d6 to your computer and use it in GitHub Desktop.
Save matthewoestreich/a7302d7c9e7e610524ed68c339c5e2d6 to your computer and use it in GitHub Desktop.
Vanilla Node server demonstrating the Node event loop
const http = require("http");
const { log } = console;
// This just lets us block the event loop
const workFor = 5 // seconds
const work = (s = workFor) => new Promise(r => setTimeout(r, s * 1000));
const appPort = 8888
let reqCount = 0
const server = http.createServer(async (req, res) => {
if (req.method === "GET") {
const reqId = ++reqCount;
log(`REQ:${reqId} : ~working : for ${workFor} seconds`);
// Simulate doing something - `await` will block here
await work()
log(`REQ:${reqId} : *done`);
res.end(`<h1>Done REQ:${reqId}</h1>`);
}
res.end()
});
server.listen(appPort, () => log(`App listening on port ${appPort}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment