在 nodejs 中,如何检查端口是否正在侦听或正在使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29860354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In nodejs, how do I check if a port is listening or in use
提问by rocky
I'll be very specific here in the hope that folks who understand this can edit to rephrase to the general situation.
我将在这里非常具体,希望了解这一点的人可以编辑以重新表述一般情况。
Currently when you run "node debug", it spawns a process to listen on port 5858. Then in the parent, a connection is attempted to that port.
当前,当您运行“节点调试”时,它会生成一个进程来侦听端口 5858。然后在父端口中,尝试连接到该端口。
However if you have another "node debug" session running, currently "node debug" hangs because that port is in use.
但是,如果您正在运行另一个“节点调试”会话,则当前“节点调试”将挂起,因为该端口正在使用中。
Specifically the message you see is:
具体而言,您看到的消息是:
$ node debug example/gcd.js 3 5
< debugger listening on port 5858 >
connecting...
Better would be for it to detect that the port is in use (without a connecting to it which might mess up another client that is trying to connect that existing debugger).
最好让它检测到端口正在使用中(没有连接到它,这可能会弄乱另一个试图连接现有调试器的客户端)。
Edit:The accepted solution is now in trepanjs.
编辑:接受的解决方案现在在trepanjs 中。
See also Node JS - How Can You Tell If A Socket Is Already Open With The Einaros WS Socket Module?
回答by rocky
A variation on the following is what I used:
以下是我使用的变体:
var net = require('net');
var portInUse = function(port, callback) {
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.listen(port, '127.0.0.1');
server.on('error', function (e) {
callback(true);
});
server.on('listening', function (e) {
server.close();
callback(false);
});
};
portInUse(5858, function(returnValue) {
console.log(returnValue);
});
The actual commit which is a little more involved is https://github.com/rocky/trepanjs/commit/f219410d72aba8cd4e91f31fea92a5a09c1d78f8
涉及更多的实际提交是https://github.com/rocky/trepanjs/commit/f219410d72aba8cd4e91f31fea92a5a09c1d78f8
回答by Trott
You should be able to use the node-netstatmoduleto detect ports that are being listened to. Unfortunately, it seems that it only supports Windows and Linux, as is. However, the changes that would be required to have it support OS X do not look to be terribly large.UPDATE: It now supports OS X...er macOS...er whatever they're calling it now.
您应该能够使用该node-netstat模块来检测正在侦听的端口。不幸的是,它似乎只支持 Windows 和 Linux。但是,使其支持 OS X 所需的更改看起来并不大。更新:它现在支持 OS X...er macOS...er 不管他们现在叫它什么。
回答by Terry Su
Use inner http module:
使用内部 http 模块:
const isPortFree = port =>
new Promise(resolve => {
const server = require('http')
.createServer()
.listen(port, () => {
server.close()
resolve(true)
})
.on('error', () => {
resolve(false)
})
})

