Node.js on multi-core machines

前端 未结 15 1310
猫巷女王i
猫巷女王i 2020-11-22 07:46

Node.js looks interesting, BUT I must miss something - isn\'t Node.js tuned only to run on a single process and thread?

Then how does it scale for m

15条回答
  •  粉色の甜心
    2020-11-22 08:14

    Node Js is supporting clustering to take full advantages of your cpu. If you are not not running it with cluster, then probably you are wasting your hardware capabilities.

    Clustering in Node.js allows you to create separate processes which can share same server port. For example, if we run one HTTP server on Port 3000, it is one Server running on Single thread on single core of processor.

    Code shown below allow you to cluster your application. This code is official code represented by Node.js.

    var cluster = require('cluster');
    var numCPUs = require('os').cpus().length;
    
    if (cluster.isMaster) {
        // Fork workers.
        for (var i = 0; i < numCPUs; i++) {
            cluster.fork();
        }
    
        Object.keys(cluster.workers).forEach(function(id) {
            console.log("I am running with ID : " + cluster.workers[id].process.pid);
        });
    
        cluster.on('exit', function(worker, code, signal) {
            console.log('worker ' + worker.process.pid + ' died');
        });
    } else {
    
        //Do further processing.
    }
    

    check this article for the full tutorial

提交回复
热议问题