我的终端一直出错,"error address already in use :::5000"

I keep getting an error in my terminal, "error address already in use :::5000"

我正在学习 node.js 速成课程,我开始学习创建服务器的部分,但出于某种原因,每次我尝试 运行 node index是我的 js 文件名我收到错误:

address already in use :::5000

我查看了类似的问题并尝试关闭该特定端口,但似乎无济于事。

if (req.url === '/') {
  fs.readFile(
    path.join(__dirname, 'public', 'index.html'),
    (err, content) => {
      if (err) throw err;
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(content);
    }
  );
}

    
const PORT = process.env.PORT || 5000;

server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
   node index 
    node:events:504
          throw er; // Unhandled 'error' event
          ^
    
    Error: listen EADDRINUSE: address already in use :::5000
        at Server.setupListenHandle [as _listen2] (node:net:1330:16)
        at listenInCluster (node:net:1378:12)
        at Server.listen (node:net:1465:7)
        at Object.<anonymous> (/Users/zacdistant/Documents/GUIDES AND TUTORIALS/Node JS Crash Course/index.js:91:8)
        at Module._compile (node:internal/modules/cjs/loader:1097:14)
        at Object.Module._extensions..js (node:internal/modules/cjs/loader:1151:10)
        at Module.load (node:internal/modules/cjs/loader:975:32)
        at Function.Module._load (node:internal/modules/cjs/loader:822:12)
        at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
        at node:internal/main/run_main_module:17:47
    Emitted 'error' event on Server instance at:
        at emitErrorNT (node:net:1357:8)
        at processTicksAndRejections (node:internal/process/task_queues:83:21) {
      code: 'EADDRINUSE',
      errno: -48,
      syscall: 'listen',
      address: '::',
      port: 5000
    }

如果您在 Mac 上,端口 5000 和 7000 已被控制中心与 AirPlay reveicer 使用:

lsof -i :5000                                                              
COMMAND   PID USER   FD   TYPE  DEVICE              SIZE/OFF NODE NAME
ControlCe 479 ****   26u  IPv4  0xa2d0e96b616f779d  0t0      TCP  *:commplex-main (LISTEN)
ControlCe 479 ****   27u  IPv6  0xa2d0e96693d0bc65  0t0      TCP  *:commplex-main (LISTEN)

要解决此问题,您必须更改服务器中使用的端口,如 const PORT = process.env.PORT || 9000;,或 turn off the AirPlay receiver。此外,如果您想事先检查端口是否可用,运行 netstat -anv -p tcp.

正如@jamomani 所解释的那样Mac 使用控制中心与 AirPlay 接收器一起使用的端口 5000 和 7000

要解决此问题,您必须更改服务器中使用的端口,例如 const PORT = process.env.PORT || 9000;,或关闭 AirPlay 接收器。此外,如果您想事先检查端口是否空闲,运行 netstat -anv -p tcp.