Created
November 17, 2020 22:04
-
-
Save matthewoestreich/a7302d7c9e7e610524ed68c339c5e2d6 to your computer and use it in GitHub Desktop.
Vanilla Node server demonstrating the Node event loop
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
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