Last active
October 15, 2019 02:21
-
-
Save Phrogz/8e6e7401705141f31510aba6bd2e1074 to your computer and use it in GitHub Desktop.
Delayed Node.js response
This file contains 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
// 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 | |
} | |
}) |
This file contains 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
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