错误:在nodejs中侦听EADDRINUSE

Error: listen EADDRINUSE in nodejs

本文关键字:EADDRINUSE nodejs 错误      更新时间:2023-09-26

我已经使用在sublime中创建了javascript构建系统

然后我用代码运行服务器

var server = require('http');
function engine(request, response){
    response.writeHead(200,  {'Content-Type': 'text/plain'});
    response.end("Hello");
}
server.createServer(engine).listen(3000);

但当我进行更改时,例如将Hello更改为Hello World并刷新浏览器时,这没有任何意义,当我尝试重新运行(f7)时,它会抛出一个异常

events.js:141
      throw er; // Unhandled 'error' event
      ^
Error: listen EADDRINUSE :::3000
    at Object.exports._errnoException (util.js:870:11)
    at exports._exceptionWithHostPort (util.js:893:20)
    at Server._listen2 (net.js:1231:14)
    at listen (net.js:1267:10)
    at Server.listen (net.js:1363:5)
    at Object.<anonymous> (C:'Users'gsiradze'Desktop'nodejs'script1.js:4:8)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
[Finished in 0.1s]

我知道这是因为3000端口正在使用,但我如何停止该端口,然后运行新代码?

我是node.js的新手,所以可以随意提出任何建议

如何运行nodejs实现?

你可以尝试使用包nodemon

npm install -g nodemon

现在,您可以通过在目录中键入nodemon来启动节点应用程序。如果您现在更改并保存文件,服务器将自动重新启动您的服务器。

如果您不想使用nodemon,请使用ctrl+c 关闭服务器

server.createServer(engine).listen(3000);

这就是您所说的端口所在的位置,您可以将端口更改为任何其他端口。

要重新运行您的代码,我认为您可以使用控制台。您可以按ctrl+C停止进程,然后使用节点名OfYoursServerFile.js 再次运行它

使用lsof -w -n -i tcp:3000在3000上查找进程的PID然后,用第一个命令返回的PID,用kill -9 PID切换PID来杀死它。

You need to get the PID of node service
You can do that by running this command on your terminal
    ps aux | grep node
it will give you  id of running node process
and the you can use 
    kill -9 <id of node process>
to stop node process and then try again to run your node server 

要么Ctrl+C前台进程,要么使用pidof node找到正在运行的进程的ID,然后杀死它(kill pid)。即使您使用forever或以其他方式在后台运行,这也会起作用。