Reputation: 53
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
?
Upvotes: 3
Views: 4227
Reputation: 33409
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.
Upvotes: 11