Node.js on multi-core machines

前端 未结 15 1613
猫巷女王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:24

    You may run your node.js application on multiple cores by using the cluster module on combination with os module which may be used to detect how many CPUs you have.

    For example let's imagine that you have a server module that runs simple http server on the backend and you want to run it for several CPUs:

    // Dependencies.
    const server = require('./lib/server'); // This is our custom server module.
    const cluster = require('cluster');
    const os = require('os');
    
     // If we're on the master thread start the forks.
    if (cluster.isMaster) {
      // Fork the process.
      for (let i = 0; i < os.cpus().length; i++) {
        cluster.fork();
      }
    } else {
      // If we're not on the master thread start the server.
      server.init();
    }

提交回复
热议问题