我们正在使用带有 socket.io 的 Nodejs 开发 WebSocket 服务器
我使用了 HTTP 类中的 createServer 方法,然后按如下方式监听端口:
var server = http.createServer();
server.listen(port, function () {
...
}
现在的问题是我只有服务名称 并且收听服务不起作用:
var server = http.createServer();
server.listen(service, function () {
...
}
所以我需要读取和解析文件/etc/services 以获取与服务关联的端口,如下所示:
var str = fs.readFileSync(filename).toString();
var serviceline = str.match( port+".*tcp" );
var port = serviceline[0].match( "[0-9]+" )
是否有更简单的方法从服务中获取端口?
提前致谢
让-玛丽
最佳答案
您可以使用 find-process从进程中查找端口,反之亦然
命令行使用
npm install find-process -g
Usage: find-process [options] <keyword>
Options:
-V, --version output the version number
-t, --type <type> find process by keyword type (pid|port|name)
-p, --port find process by port
-h, --help output usage information
Examples:
$ find-process node # find by name "node"
$ find-process 111 # find by pid "111"
$ find-process -p 80 # find by port "80"
$ find-process -t port 80 # find by port "80"
代码使用
npm install find-process --save
const find = require('find-process');
find('pid', 12345)
.then(function (list) {
console.log(list);
}, function (err) {
console.log(err.stack || err);
})
我已经使用它从端口中找到进程,但我认为它提供了一种相反的方法,或者您可以浏览到它的 repo 并选择您需要的代码。
关于javascript - 如何使用nodejs从服务名称中获取端口号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49447449/