發(fā)布于:2021-02-15 00:00:58
0
417
0
Node.js已經(jīng)成為創(chuàng)建服務(wù)或充當(dāng)服務(wù)的實(shí)用工具的不可思議的工具。通常是npm start,等一下,你會(huì)看到這個(gè)實(shí)用程序提供了一個(gè)地址和端口;一個(gè)很好的例子是localhost:8000。關(guān)于此模式,讓我感到困擾的一件事是,如果您有許多基于服務(wù)的實(shí)用程序,您最終會(huì)遇到“正在使用的端口”錯(cuò)誤,然后您需要查看所有的實(shí)用程序,以確定應(yīng)該關(guān)閉哪一個(gè)。
有一個(gè)簡(jiǎn)單的解決方案: Node Port Scanner。該實(shí)用程序提供查找給定主機(jī)上正在使用或可用端口的方法!
使用端口掃描器
解決端口沖突的最常見(jiàn)用例是findAPortNotInUse:
var portscanner = require('portscanner');
// 127.0.0.1 is the default hostname; not required to provide
portscanner.findAPortNotInUse([3000, 3010], '127.0.0.1').then(port => {
console.log(`Port ${port} is available!`);
// Now start your service on this port...
});
提供一系列端口,然后從第一個(gè)可用端口開(kāi)始很簡(jiǎn)單-不再發(fā)生沖突。
您還可以檢查給定端口的狀態(tài),或檢查正在使用的端口:
// Get port status
portscanner.checkPortStatus(3000, '127.0.0.1').then(status => {
// Status is 'open' if currently in use or 'closed' if available
console.log(status);
});
// Find port in use
portscanner.findAPortInUse([3000, 3005, 3006], '127.0.0.1').then(port => {
console.log('PORT IN USE AT: ' + port);
});
使用此端口掃描程序?qū)嵱贸绦蚍浅:?jiǎn)單,并且是使服務(wù)在任何可用端口上運(yùn)行的最簡(jiǎn)單方法。不必要的硬編碼端口使用只會(huì)導(dǎo)致失?。?/span>
作者介紹
熱門(mén)博客推薦