Node.JS应用程序出现ERR_SERVER_ALREADY_LISTENING错误,但仅适用于10.2.1?

y4ekin9u  于 2023-02-08  发布在  Node.js
关注(0)|答案(2)|浏览(113)

我有一个运行在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);
}
sauutmhj

sauutmhj1#

总结

这个错误发生在我用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);
  });
});

我得到错误:
错误[错误服务器已侦听]:已多次调用Listen方法而未关闭。
问题是启动服务器和连接到数据库是异步的,但单元测试是同步运行的。

修复:

我不确定是否有更好的方法来解决这个问题,但这就是我解决这个问题的方法。在我的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()钩子:

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

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

7bsow1i62#

检查:
.listen()方法只能使用一次;只需注解行server.listen(port);

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.listen('listening', onListening);

相关问题