Node.js / express: respond immediately to client request and continue tasks in nextTick

前端 未结 3 2064
情歌与酒
情歌与酒 2021-02-06 09:20

I would like to separate server high consuming CPU task from user experience:

./main.js:

var express = require(\'express\');
var Test = require(\'./resou         


        
3条回答
  •  遥遥无期
    2021-02-06 10:09

    A good solution is to use child_process.fork(): it allows you to execute another JavaScript file of your app in a different Node instance, and thus in a different event loop. Of course, you can still communicate between the two processes by sending messages: so, from your UI process, you can send a message to the forked process to ask it to execute something.

    For example, in ui.js:

    var ChildProcess = require('child_process');
    var heavyTaskWorker = ChildProcess.fork('./heavyTaskWorker.js');
    ...
    var message = {
        operation: "longOperation1",
        parameters: {
            param1: "value1",
            ...
        }
    };
    heavyTaskWorker.send(message);
    

    And in heavyTaskWorker.js:

    process.on('message', function (message) {
        switch (message.operation) {
        case 'longOperation1':
            longOperation1.apply(null, message.parameters);
            break;
        ...
        }
    });
    

    Tested here, and it works fine!

    Hope that helps!

提交回复
热议问题