node.js - 在 Node.js 中使用集群时出现错误

标签 node.js ubuntu-18.04

我在 node.js 中使用集群来创建多个工作线程,但根据我的代码,我收到以下错误。

错误:

Error: bind EADDRINUSE null:3000
    at listenOnMasterHandle (net.js:1420:16)
    at rr (internal/cluster/child.js:121:12)
    at Worker.send (internal/cluster/child.js:88:7)
    at process.onInternalMessage (internal/cluster/utils.js:42:8)
    at emitTwo (events.js:131:20)
    at process.emit (events.js:214:7)
    at emit (internal/child_process.js:762:12)
    at _combinedTickCallback (internal/process/next_tick.js:142:11)
    at process._tickCallback (internal/process/next_tick.js:181:9)

下面给出了我的服务器代码文件。

app.js:

const express = require('express'),
      http    = require('http'),
      cors    = require('cors'),
      bodyParser = require('body-parser'),
      xss    = require('xss-clean'),
      helmet = require('helmet'),
      cluster = require('cluster'),
      os     = require('os'),
      mongoSanitize = require('express-mongo-sanitize');



    const app = express();
    app.use(bodyParser.json({limit:'25mb'}));
    app.use(cors());
    app.use(bodyParser.urlencoded({limit: '25mb', extended: true}));
    app.use(xss());
    app.use(mongoSanitize());
    app.use(express.static(__dirname+'/public'));
    
    
    const server = http.createServer(app);
    
    
    if(cluster.isMaster) {
        let length = os.cpus().length;
    
        for(let i = 0; i < length; i++) {
            cluster.fork();
        }
    } else {
    
        app.get('/', (req,res) => {
            res.status(200).render('index.html');
        })
    }
    
    
    server.listen('3000',() => {
        console.log('server is running ar port 3000')
    });

我正在使用以下命令来运行我的服务器。

nodemon npm start

这里我的问题是,当我实现集群来创建多个工作人员时,会出现这些错误,但如果不使用集群,则该文件可以正确运行。我需要解决这个错误。

最佳答案

app.js 的条件语句需要包装所有 Express 应用程序功能,因此更新后的文件将如下所示。

else {
    const app = express();
    app.use(express.static(__dirname + '/public'));
    app.get('/', (req, res) => {
        res.status(200).render('index.html');
    });
    const server = http.createServer(app);
    server.listen('3000', () => {
        console.log('server is running ar port 3000')
    });
}

您可以看看Example link .

关于node.js - 在 Node.js 中使用集群时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62725534/

相关文章:

node.js - 尝试从一条 Express 路线获取内容作为 jsreports 中 pdf 报告的内容

linux - 在内核 debians 中包含 objTools(linux-headers 和 linux-image)

node.js - AWS Lambda 错误 - "errorType": "string", "errorMessage": "handled"

node.js - 使用 mongoose 插入或更新到 Mongodb 并在更新时修改内部元素

javascript - ubunu 中的 Angular CLI 安装错误 - 当我尝试在我的 ubuntu 机器中运行 angular CLI 命令时出现错误

ssl - OpenSSL 无法建立 SSL 连接,因为不支持的协议(protocol)

perl - 为什么我无法在 Ubuntu 18.04 上安装 Perl Net-SNMP

linux - bash 终端和 Goland IDE 中的不同 GOPATH

node.js - Db的数据不断增加

node.js - 将 Sequelize 查询中的数据保存为变量中的纯 JavaScript 对象?