In nodejs, how do I check if a port is listening or in use

后端 未结 3 1668
再見小時候
再見小時候 2021-02-19 23:20

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 sp

3条回答
  •  春和景丽
    2021-02-20 00:04

    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

提交回复
热议问题