發(fā)布于:2021-02-15 00:00:58
0
417
0
Node.js已經(jīng)成為創(chuàng)建服務(wù)或充當(dāng)服務(wù)的實用工具的不可思議的工具。通常是npm start,等一下,你會看到這個實用程序提供了一個地址和端口;一個很好的例子是localhost:8000。關(guān)于此模式,讓我感到困擾的一件事是,如果您有許多基于服務(wù)的實用程序,您最終會遇到“正在使用的端口”錯誤,然后您需要查看所有的實用程序,以確定應(yīng)該關(guān)閉哪一個。
有一個簡單的解決方案: Node Port Scanner。該實用程序提供查找給定主機上正在使用或可用端口的方法!
使用端口掃描器
解決端口沖突的最常見用例是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...
});
提供一系列端口,然后從第一個可用端口開始很簡單-不再發(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ū)嵱贸绦蚍浅:唵?,并且是使服?wù)在任何可用端口上運行的最簡單方法。不必要的硬編碼端口使用只會導(dǎo)致失敗!