Nodejs 用webstorm调试或者运行,如果有监听端口,那么第二次就会报错,错误内容见正文.
Nodejs 用webstorm调试或者运行,如果有监听端口,那么第二次就会报错,错误内容见正文.
/usr/local/bin/node app.js
events.js:71 throw arguments[1]; // Unhandled ‘error’ event ^ Error: listen EADDRINUSE at errnoException (net.js:770:11) at Server._listen2 (net.js:910:14) at listen (net.js:937:10) at Server.listen (net.js:986:5) at Object.<anonymous> (/Users/username/WebstormProjects/HelloWorld/app.js:32:24) at Module._compile (module.js:449:26) at Object.Module._extensions…js (module.js:467:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Module.runMain (module.js:492:10)
Process finished with exit code 1
用的是webstorm自带的模板创建的项目
如果要重启的话,请按Run面版上的Rerun (Ctrl+F5)
检查前一次运行的app.js是否关闭,先关闭前一次的再运行,就不会占用端口了。
同样问题待解决 不收到去关闭之前的进程不行吗
这个问题很简单,点下面 》符号切换回之前的调试就可以了,之前的调试还在运行。
当使用WebStorm调试或运行Node.js应用时,如果应用试图监听一个已经被占用的端口(如8080),会出现EADDRINUSE
错误。这是因为Node.js尝试绑定到一个已经有其他进程占用的端口。
解决方案
方法一:更改监听端口
最简单的解决方法是修改你的应用以监听不同的端口。
示例代码
const port = process.env.PORT || 3000; // 修改为你想要使用的端口,比如3000
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(port, () => console.log(`Server running at http://localhost:${port}/`));
方法二:确保前一个实例已经关闭
如果你的应用需要频繁重启,可以确保在启动新实例之前,前一个实例已经完全关闭。
示例代码
const http = require('http');
let server;
function startServer() {
const port = process.env.PORT || 3000;
server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(port, () => console.log(`Server running at http://localhost:${port}/`));
}
startServer();
// 当需要停止服务器时
process.on('SIGINT', () => {
server.close(() => {
console.log('Server closed');
process.exit();
});
});
以上代码通过监听SIGINT
信号(通常由Ctrl+C触发)来优雅地关闭服务器,从而避免端口被占用的问题。