您经常会看到Node的示例hello world代码,该代码创建Http Server,开始侦听端口,然后执行以下操作:
console.log('Server is listening on port 8000');
但理想情况下,您希望这样做:
console.log('Server is listening on port ' + server.port);
如何在调用前不将服务器号存储在变量中的情况下检索服务器当前正在侦听的端口server.listen()?
server.listen()
我之前已经看过这件事,但是在Node文档中找不到。也许这是表达的特定内容?
Express 4.x答案:
Express 4.x(根据下面的Tien Do回答)现在将app.listen()视为异步操作,因此listener.address()将仅在app.listen()的回调中返回数据:
var app = require('express')(); var listener = app.listen(8888, function(){ console.log('Listening on port ' + listener.address().port); //Listening on port 8888 });
快递3答案:
我认为您正在寻找这个(特定于表达?):
console.log("Express server listening on port %d", app.address().port)
通过express命令创建目录结构时,您可能已经看到了这一点(下一行):
express
alfred@alfred-laptop:~/node$ express test4 create : test4 create : test4/app.js create : test4/public/images create : test4/public/javascripts create : test4/logs create : test4/pids create : test4/public/stylesheets create : test4/public/stylesheets/style.less create : test4/views/partials create : test4/views/layout.jade create : test4/views/index.jade create : test4/test create : test4/test/app.test.js alfred@alfred-laptop:~/node$ cat test4/app.js /** * Module dependencies. */ var express = require('express'); var app = module.exports = express.createServer(); // Configuration app.configure(function(){ app.set('views', __dirname + '/views'); app.use(express.bodyDecoder()); app.use(express.methodOverride()); app.use(express.compiler({ src: __dirname + '/public', enable: ['less'] })); app.use(app.router); app.use(express.staticProvider(__dirname + '/public')); }); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); // Routes app.get('/', function(req, res){ res.render('index.jade', { locals: { title: 'Express' } }); }); // Only listen on $ node app.js if (!module.parent) { app.listen(3000); console.log("Express server listening on port %d", app.address().port) }