如何检查NodeJS中的端口是否繁忙? [英] How can I check if port is busy in NodeJS?
本文介绍了如何检查NodeJS中的端口是否繁忙?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检查端口是否正常 localhost
?
是有没有标准算法?我正在考虑向该网址发出 http
请求,并检查响应状态代码是否不是 404
。
Is there any standard algorithm? I am thinking at making a http
request to that url and check if response status code is not 404
.
推荐答案
您可以尝试启动服务器,无论是TCP还是HTTP,都没关系。然后你可以尝试开始监听端口,如果失败,检查错误代码是否为 EADDRINUSE
。
You could attempt to start a server, either TCP or HTTP, it doesn't matter. Then you could try to start listening on a port, and if it fails, check if the error code is EADDRINUSE
.
var net = require('net');
var server = net.createServer();
server.once('error', function(err) {
if (err.code === 'EADDRINUSE') {
// port is currently in use
}
});
server.once('listening', function() {
// close the server if listening doesn't fail
server.close();
});
server.listen(/* put the port to check here */);
使用一次性事件处理程序,您可以将其包装成异步检查函数。
With the single-use event handlers, you could wrap this into an asynchronous check function.
这篇关于如何检查NodeJS中的端口是否繁忙?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文