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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With