Last active
February 1, 2020 06:37
-
-
Save krisselden/44d4f78d1cf5e342996ecc11e684c58a to your computer and use it in GitHub Desktop.
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 vm = require("vm"); | |
const fs = require("fs"); | |
function scheduleLoop(schedule) { | |
function loop(sum = 0) { | |
schedule(() => loop(doSomeWork(sum))); | |
} | |
schedule(loop); | |
} | |
function promiseLoop(Promise) { | |
scheduleLoop(fn => Promise.resolve().then(fn)); | |
} | |
http | |
.createServer((req, res) => { | |
switch (req.url) { | |
case "/ping": | |
res.statusCode = 200; | |
res.end("pong"); | |
break; | |
case "/tick": | |
scheduleLoop(process.nextTick); | |
break; | |
case "/immediate": | |
scheduleLoop(setImmediate); | |
break; | |
case "/timeout": | |
scheduleLoop(fn => setTimeout(fn, 0)); | |
break; | |
case "/asyncfn": | |
scheduleLoop(async fn => await fn()); | |
break; | |
case "/promise": | |
promiseLoop(Promise); | |
break; | |
case "/rsvp": | |
promiseLoop(require("rsvp").Promise); | |
break; | |
case "/rsvpvm": | |
promiseLoop(vmContext("rsvp").RSVP.Promise); | |
break; | |
default: | |
res.statusCode = 404; | |
res.end("not found"); | |
} | |
}) | |
.listen(4321) | |
.on("listening", () => { | |
console.log("ping http://localhost:4321/ping"); | |
console.log("nextTick loop http://localhost:4321/tick"); | |
console.log("immediate loop http://localhost:4321/immediate"); | |
console.log("timeout 0 loop http://localhost:4321/timeout"); | |
console.log("async func loop http://localhost:4321/asyncfn"); | |
console.log("promise loop http://localhost:4321/promise"); | |
console.log("RSVP loop http://localhost:4321/rsvp"); | |
console.log("RSVP vm loop http://localhost:4321/rsvpvm"); | |
}) | |
.on("error", e => console.error("%O", e)); | |
function vmContext(mod) { | |
const filename = require.resolve(mod); | |
const code = fs.readFileSync(filename, "utf8"); | |
const script = new vm.Script(code, { | |
filename | |
}); | |
const context = vm.createContext({ | |
setTimeout | |
}); | |
script.runInContext(context); | |
return context; | |
} | |
function doSomeWork(sum = 0) { | |
let array = []; | |
for (let i = 0; i < 10000; i++) { | |
array.push(i); | |
} | |
return array.reduce((a, b) => a + b, sum); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment