最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Express.js getting address and port while still executing - Stack Overflow

programmeradmin0浏览0评论

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 .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?

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./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?

Share Improve this question edited Jan 1, 2015 at 14:02 Scimonster 33.4k10 gold badges79 silver badges91 bronze badges asked Jan 1, 2015 at 12:33 alexander_the_greatalexander_the_great 531 silver badge4 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

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.

发布评论

评论列表(0)

  1. 暂无评论