爲了解決 ssr 工具 起多個服務的時候端口被佔用的狀況。分享研究的代碼片斷。git
// 檢測port是否被佔用
function probe(port, callback) {
var server = net.createServer().listen(port)
var calledOnce = false
var timeoutRef = setTimeout(function () {
calledOnce = true
callback(false,port)
}, 2000)
timeoutRef.unref()
var connected = false
server.on('listening', function() {
clearTimeout(timeoutRef)
if (server)
server.close()
if (!calledOnce) {
calledOnce = true
callback(true,port)
}
})
server.on('error', function(err) {
clearTimeout(timeoutRef)
var result = true
if (err.code === 'EADDRINUSE')
result = false
if (!calledOnce) {
calledOnce = true
callback(result,port)
}
})
}
function server(_port){
var pt = _port || __port;
probe(pt,function(bl,_pt){
// 端口被佔用 bl 返回false
// _pt:傳入的端口號
if(bl === true){
// ssr(_pt)
server = http.createServer(connListener);
server = server.listen(parseInt(_pt, 10));
console.log("\n Static file server running at" + "\n\n=> http://localhost:" + _pt + '\n');
}else{
server(_pt+1)
}
})
}複製代碼