Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js getting address and port while still executing

I've read many posts on Nodejs and Expressjs for that matter but I still don't understand how this works:

This is the basic Hello World application with Express.js (taken from http://expressjs.com/starter/hello-world.html).

var express = require('express')
var app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')
})

var server = app.listen(3000, function () {

var host = server.address().address
var port = server.address().port

console.log('Example app listening at http://%s:%s', host, port)

})

How are we able to get host and port using server when we are still in the process of getting what we'll eventually bind to the var server?

like image 290
alexander_the_great Avatar asked Jan 25 '26 17:01

alexander_the_great


1 Answers

Because it's asynchronous. The callback is only being run later, after server is defined and initialized.

var server = app.listen(3000, function () {

    var host = server.address().address
    var port = server.address().port

    console.log('Example app listening at http://%s:%s', host, port)

})

Proper indenting sometimes helps see this.

like image 171
Scimonster Avatar answered Jan 28 '26 06:01

Scimonster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!