NodeJs how to create a non-blocking computation

前端 未结 5 1697
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-10 01:53

I am trying to get my head around creating a non-blocking piece of heavy computation in nodejs. Take this example (stripped out of other stuff):

http.createS         


        
5条回答
  •  青春惊慌失措
    2020-12-10 02:36

    We (Microsoft) just released napajs that can work with Node.js to enable multithreading JavaScript scenarios in the same process.

    your code will then look like:

    var napa = require('napajs');
    
    // One-time setup. 
    // You can change number of workers per your requirement. 
    var zone = napa.zone.create('request-worker-pool', { workers: 4 });
    
    http.createServer(function(req, res) {
        console.log(req.url);
    
        zone.execute((request) => {
            var result = null;
            // Do heavy computation to get result from request
            // ...
            return result;
        }, [req]).then((result) => {
            res.end(result.value);
        }
    }).listen(8080, function() { console.log("ready"); });
    

    You can read this post for more details.

提交回复
热议问题