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

前端 未结 3 2060
情歌与酒
情歌与酒 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 09:58

    Thakns for Peter Lyons help, finally the main problem was firefox buffer: response was not so long as to flush it (so firefox kept waiting).

    Anyway, for hight CPU performing tasks, node would keep hanged until finishing, so will not be attending new requests. If someone needs it, it can be achieved by forking (with child_process, see sample in http://nodejs.org/api/child_process.html)

    Have to say that change of context by forking could take longer than splitting the task in different ticks.

    ./resources/test.js:

    var child = require('child_process');
    function Test() {}
    module.exports = Test;
    
    Test.testAsync = function(req, res) {
      res.send(200, "Hello world, this should be sent inmediately");
      var childTask = child.fork('child.js');
      childTask.send({ hello: 'world' });
    };
    

    ./resources/child.js:

    process.on('message', function(m) {
      console.log('CHILD got message:', m);
    });
    
    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2021-02-06 10:23

    Try waiting instead of hogging the CPU:

    res.send("Hello world, this should be sent inmediately");
    console.log("Response sent.");
    setTimeout(function() {
      console.log("After-response code running!");
    }, 3000);
    

    node.js is single-threaded. If you lock up the CPU with a busy loop, the whole thing grinds to a halt until that is done.

    0 讨论(0)
提交回复
热议问题