Skip to content

Instantly share code, notes, and snippets.

@Phrogz
Last active October 15, 2019 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Phrogz/8e6e7401705141f31510aba6bd2e1074 to your computer and use it in GitHub Desktop.
Save Phrogz/8e6e7401705141f31510aba6bd2e1074 to your computer and use it in GitHub Desktop.
Delayed Node.js response
// Storing response objects for delayed responses
const responseByMessage = {}
// A forked process that does some necessary heavy lifting
const worker = require('child_process').fork(
require('path').resolve('worker.js'), [],
{stdio:['inherit', 'inherit', 'inherit', 'ipc']}
)
require('http').createServer(function (req, res) {
if (req.url=='/') {
// ...
} else if (req.url=='/scenarios') {
responseByMessage.scenarios = res
worker.send({action:'scenarios'})
}
}).listen(8080);
worker.on('message', msg => {
switch (msg.action) {
case 'scenarios':
let res = responseByMessage.scenarios
if (res) {
res.writeHead(200, {'Content-Type':'application/json'})
res.end(JSON.stringify(msg.data))
delete responseByMessage.scenarios
}
break
}
})
if (process.send) {
process.on('message', msg => {
switch (msg.action) {
case 'scenarios':
process.send({action:'scenarios', data:buildScenarioList()})
break;
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment