NodeJS: How to get the server's port?

后端 未结 19 1593
醉梦人生
醉梦人生 2020-12-02 05:47

You often see example hello world code for Node that creates an Http Server, starts listening on a port, then followed by something along the lines of:

conso         


        
19条回答
  •  猫巷女王i
    2020-12-02 06:21

    In the current version (v0.5.0-pre) the port seems to be available as a property on the server object, see http://nodejs.org/docs/v0.4.7/api/net.html#server.address

    var server = http.createServer(function(req, res) {
        ...
    }
    
    server.listen(8088);
    console.log(server.address());
    console.log(server.address().address);
    console.log(server.address().port);
    

    outputs

    { address: '0.0.0.0', port: 8088 }
    0.0.0.0
    8088
    

提交回复
热议问题