gpt4 book ai didi

javascript - Node JS : How to get the server's port?

转载 作者:IT老高 更新时间:2023-10-28 21:46:48 25 4
gpt4 key购买 nike

你经常会看到 Node 的示例 hello world 代码,它创建一个 Http 服务器,开始监听一个端口,然后是类似以下内容的代码:

console.log('Server is listening on port 8000');

但理想情况下你会想要这个:

console.log('Server is listening on port ' + server.port);

如何在调用 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 命令创建目录结构时,您可能已经看到了这个(底线):

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)
}

关于javascript - Node JS : How to get the server's port?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4840879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com