gpt4 book ai didi

node.js - Node.JS 应用程序出现 ERR_SERVER_ALREADY_LISTENING 错误,但仅限 10.2.1?

转载 作者:太空宇宙 更新时间:2023-11-04 02:45:39 27 4
gpt4 key购买 nike

我有一个在 Ubuntu Linux 18.04 (Bionic) 上运行的 Node.JS 应用程序。它在 Node.JS 版本 8.11.1 上运行良好;完全没有错误。但是当我尝试使用 10.2.1 运行它时,在我创建的服务器上执行 listen() 方法时,我立即收到以下错误:

    net.js:1416
throw new ERR_SERVER_ALREADY_LISTEN();
^

Error [ERR_SERVER_ALREADY_LISTEN]: Listen method has been called more than once without closing.
at Server.listen (net.js:1416:11)
at Object.<anonymous> (./web-site/bin/www:56:8)
at Module._compile (internal/modules/cjs/loader.js:699:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
at startup (internal/bootstrap/node.js:238:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:572:3)
Waiting for the debugger to disconnect...

我对此进行了三次检查,但我只调用了一次listen()方法。此外,如果这确实是问题所在,那么该代码将无法在旧版本的 Node.JS 上运行。

有人能想到为什么会发生这种情况以及我该如何解决它吗?

这是我的 bin/www 文件的代码。这是当我运行应用程序时在调试配置中启动的文件:

#!/usr/bin/env node

/**
* Web start file that supports SSL and listens for traffic on port 7300.
*/

/**
* Module dependencies.
*/

var app = require('../app');
var debug = require('debug')('aux:server');

/**
* Get port from environment and store in Express. If not, use port 3000.
*/

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
* Create the HTTPS server.
*/

var fs = require('fs');
var https = require('https');

// Get the location of the private key and fullchain files for SSL support
// from the environment.
var privkeyPath = process.env.PRIVKEY_PATH;
var fullchainPath = process.env.FULLCHAIN_PATH;

// Validate them.
if (!fs.existsSync(privkeyPath))
throw new Error("Invalid private key file path: " + privkeyPath);

if (!fs.existsSync(fullchainPath))
throw new Error("Invalid fullchain file path: " + fullchainPath);

var options = {
key: fs.readFileSync(privkeyPath),
cert: fs.readFileSync(fullchainPath),
requestCert: true,
rejectUnauthorized: true
};

var server = https.createServer(options, app).listen(port, function(){
console.log("Certificate enabled express server listening on port " + port);
});


/**
* Listen on provided port, on all network interfaces.
*/

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
var port = parseInt(val, 10);

if (isNaN(port)) {
// named pipe
return val;
}

if (port >= 0) {
// port number
return port;
}

return false;
}

/**
* Event listener for HTTP server "error" event.
*/

function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:

throw error;
}
}

/**
* Event listener for HTTP server "listening" event.
*/

function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;

debug('Listening on ' + bind);
}

最佳答案

摘要

我在使用 Fastify 和 chai-http 进行单元测试时发生了这个错误。我试图在服务器完成启动之前执行 chai.request()

完整说明:

在测试的顶部,我有:

const server = require('../server');

server.js中是启动服务器并连接数据库的代码。

const fastify = require('fastify')(opts);
fastify.register(require('./routes'));

const start = async () => {
try {
await startServer();
} catch (err) {
logErrors(err);
}
};
start();

module.exports = fastify.server;

当我尝试进行以下单元测试时:

describe('Test', () => {
it('should respond with 404', async () => {
let res = await chai.request(server).get('/invalid-url');
expect(res).to.have.status(404);
});
});

我收到错误:

Error [ERR_SERVER_ALREADY_LISTEN]: Listen method has been called more than once without closing.

问题在于启动服务器和连接数据库是异步的,但单元测试正在同步运行。

修复:

我不确定是否有更好的方法来解决这个问题,但这就是我解决它的方法。在我的 server.js 文件中,我将其更改为:

let starting = false;
let started = false;

// Start the server!
fastify.server.start = async () => {
try {
await waitForStartInProgressToFinish();
if (!started) {
await startServer(); // This sets starting and started accordingly
}
} catch (err) {
logErrors(err);
}
};

async function waitForStartInProgressToFinish() {
let waitCount = 0;
while (starting === true && waitCount < 400) {
await new Promise(resolve => setTimeout(resolve, 5));
waitCount++;
}
}

然后在我的单元测试代码中,添加以下 before() Hook :

describe('Test', () => {
// ... Tests

before(async () => {
await server.start();
});
});

关于node.js - Node.JS 应用程序出现 ERR_SERVER_ALREADY_LISTENING 错误,但仅限 10.2.1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51218587/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com