Expiration of child processes on the express server

There are some functions on my express server that I need to run as child processes, because otherwise they will connect the server, and other people will not be able to access it. They already use the asynchronous module, but they still bind the server if they are not running as child processes.

One problem is passing them the req and res parameters.

How can I do that?

+4
source share
1 answer

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) { // Process data process.send({id: message.id, data: 'some result'}); }); 

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.

+12
source

Source: https://habr.com/ru/post/1415815/


All Articles