Javascript NodeJS:如何获取服务器的端口?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4840879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NodeJS: How to get the server's port?
提问by David Tang
You often see example hello world code for Node that creates an Http Server, starts listening on a port, then followed by something along the lines of:
您经常会看到 Node 的示例 hello world 代码,它创建了一个 Http 服务器,开始侦听端口,然后是以下内容:
console.log('Server is listening on port 8000');
But ideally you'd want this instead:
但理想情况下,你会想要这个:
console.log('Server is listening on port ' + server.port);
How do I retrieve the port the server is currently listening on without storing the number in a variable prior to calling server.listen()
?
如何检索服务器当前正在侦听的端口而不在调用之前将数字存储在变量中server.listen()
?
I've seen this done before but I can't find it in the Node documentation. Maybe it's something specific to express?
我以前见过这样做,但在 Node 文档中找不到它。可能是有什么特别想表达的?
回答by Alfred
Express 4.x answer:
表达 4.x 答案:
Express 4.x (per Tien Do's answer below), now treats app.listen() as an asynchronous operation, so listener.address() will only return data inside of app.listen()'s callback:
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
});
Express 3 answer:
表达 3 答案:
I think you are looking for this(express specific?):
我认为您正在寻找这个(具体表达?):
console.log("Express server listening on port %d", app.address().port)
You might have seen this(bottom line), when you create directory structure from express
command:
当您从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)
}
回答by dgh
In express v3.0,
在 express v3.0 中,
/* No longer valid */
var app = express.createServer();
app.listen();
console.log('Server running on %s', app.address().port);
no longer works! For Express v3.0, you should create an app and a server this way:
不再有效!对于 Express v3.0,您应该通过以下方式创建应用程序和服务器:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000);
console.log('Express server started on port %s', server.address().port);
I ran in to this issue myself and wanted to document the new syntax. This and other changes in Express v3.0 are visible at https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
我自己遇到了这个问题,想记录新的语法。Express v3.0 中的此更改和其他更改可见于https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
回答by J?rn Horstmann
In the current version (v0.5.0-pre) the port seems to be available as a property on the server object, see http://nodejs.org/docs/v0.4.7/api/net.html#server.address
在当前版本 (v0.5.0-pre) 中,端口似乎可用作服务器对象上的属性,请参阅http://nodejs.org/docs/v0.4.7/api/net.html#server.address
var server = http.createServer(function(req, res) {
...
}
server.listen(8088);
console.log(server.address());
console.log(server.address().address);
console.log(server.address().port);
outputs
产出
{ address: '0.0.0.0', port: 8088 }
0.0.0.0
8088
回答by user3348991
In case when you need a port at the time of request handling and app is not available, you can use this:
如果您在处理请求时需要一个端口并且应用程序不可用,您可以使用:
request.socket.localPort
回答by chovy
If you're using express, you can get it from the request object:
如果您使用的是 express,则可以从 request 对象中获取:
req.app.settings.port // => 8080 or whatever your app is listening at.
回答by Christian Landgren
I use this way Express 4:
我用这种方式Express 4:
app.listen(1337, function(){
console.log('Express listening on port', this.address().port);
});
By using this I don't need to use a separate variable for the listener/server.
通过使用它,我不需要为侦听器/服务器使用单独的变量。
回答by james_womack
Requiring the http module was never necessary.
从来不需要 http 模块。
An additional import of http
is not necessary in Express 3 or 4. Assigning the result of listen()
is enough.
http
在 Express 3 或 4 中不需要额外的导入。分配结果listen()
就足够了。
var server = require('express')();
server.get('/', function(req, res) {
res.send("Hello Foo!");
});
var listener = server.listen(3000);
console.log('Your friendly Express server, listening on port %s', listener.address().port);
// Your friendly Express server, listening on port 3000
Again, this is tested in Express 3.5.1 & 4.0.0. Importing http
was never necessary. The listen method returns an http server object.
https://github.com/visionmedia/express/blob/master/lib/application.js#L531
同样,这在 Express 3.5.1 和 4.0.0 中进行了测试。进口http
从来没有必要。listen 方法返回一个 http 服务器对象。
https://github.com/visionmedia/express/blob/master/lib/application.js#L531
回答by Eric Bréchemier
With latest node.js (v0.3.8-pre): I checked the documentation, inspected the server instance returned by http.createServer(), and read the source code of server.listen()...
使用最新的 node.js (v0.3.8-pre):我查看了文档,检查了 http.createServer() 返回的服务器实例,并阅读了 server.listen() 的源代码...
Sadly, the port is only stored temporarily as a local variable and ends up as an argument in a call to process.binding('net').bind() which is a native method. I did not look further.
遗憾的是,端口仅作为局部变量临时存储,最终作为调用 process.binding('net').bind() 的参数,这是一个本地方法。我没有再看下去。
It seems that there is no better way than keeping a reference to the port value that you provided to server.listen().
似乎没有比保留对您提供给 server.listen() 的端口值的引用更好的方法了。
回答by Waylon Flinn
The simplest way to convert from the old style to the new (Express 3.x) style is like this:
从旧样式转换为新(Express 3.x)样式的最简单方法是这样的:
var server = app.listen(8080);
console.log('Listening on port: ' + server.address().port);
Pre 3.x it works like this:
在 3.x 之前,它的工作方式是这样的:
/* This no longer works */
app.listen(8080);
console.log('Listening on port: ' + app.address().port);
回答by RockerFlower
req.headers.host.split(':')[1]