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

后端 未结 3 1661
再見小時候
再見小時候 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

    0 讨论(0)
  • 2021-02-20 00:15

    Use inner http module:

    const isPortFree = port =>
      new Promise(resolve => {
        const server = require('http')
          .createServer()
          .listen(port, () => {
            server.close()
            resolve(true)
          })
          .on('error', () => {
            resolve(false)
          })
      })
    
    0 讨论(0)
  • 2021-02-20 00:16

    You should be able to use the node-netstat module to detect ports that are being listened to. Unfortunately, it seems that it only supports Windows and Linux, as is. However, the changes that would be required to have it support OS X do not look to be terribly large. UPDATE: It now supports OS X...er macOS...er whatever they're calling it now.

    0 讨论(0)
提交回复
热议问题