NodeJs Cluster.Fork不是函数

时间:2019-03-16 12:21:45

标签: node.js

我使用此简单的行代码,但出现此错误。 Iam使用Node v10.15

var cluster = require('cluster');
var s = cluster.fork();

错误

TypeError: cluster.fork is not a function
    at Object.<anonymous> (C:\Users\sdss\Documents\Coding\NodeJs\a.js:17:17)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)

1 个答案:

答案 0 :(得分:1)

检查集群叉是否需要启动,cpus长度以及是否为master,请尝试以下代码

    const cluster = require('cluster');
    const http = require('http');
    const numCPUs = require('os').cpus().length;

    if (cluster.isMaster) {
      masterProcess();
    } else {
      childProcess();  
    }

    function masterProcess() {
      console.log(`Master ${process.pid} is running`);

      for (let i = 0; i < numCPUs; i++) {
        console.log(`Forking process number ${i}...`);
        cluster.fork();
      }

      process.exit();
    }

    function childProcess() {
      console.log(`Worker ${process.pid} started and finished`);

      process.exit();
    }