我在 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/