Using child_process.fork , you can send messages to child processes.
Edit: I incorrectly advised passing req
and res
as message parameters to the child process. This is not possible, since all messages to and from child processes are converted to JSON. Instead, you can save some kind of queue on your server. The following is just an example; you might want something more reliable:
child.js:
process.on('message', function(message) {
server.js:
var child_process = require('child_process'); var child = child_process.fork(__dirname + '/child.js'); var taskId = 0; var tasks = {}; function addTask(data, callback) { var id = taskId++; child.send({id: id, data: data}); tasks[id] = callback; }; child.on('message', function(message) { // Look up the callback bound to this id and invoke it with the result tasks[message.id](message.data); }); app.post('/foo', function(req, res) { addTask('some data', function(result) { res.send(result); }); });
This is a bit more, but it should work. You can quickly grow out of such a system and perhaps better serve the appropriate queue.
source share