我想从我的 Node js 服务器向终端输出一条消息,例如“Listening on port {port_#}”。
我找到了文档,例如:NodeJS: How to get the server's port? ,但他们只谈论 Express JS。
我正在使用 ConnectJS 方面进行连接。所以我的代码如下所示:
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080);
console.log("Listening on port %d", connect.address().port);
但是,这不起作用。我如何将端口记录到终端?
最佳答案
您正在尝试调用连接库的.address()
方法。这个方法不存在。它甚至不存在于 connect()
实例上。您正在寻找的方法存在于 http.Server
对象中。
当您创建连接实例时,会返回一个应用程序。当您告诉应用程序监听时,您可以提供一个回调,当应用程序开始监听时会调用该回调。使用 http.Server
作为绑定(bind)到 this
的上下文来调用此回调。
var connect = require( 'connect' )
var app = connect()
app.listen( 8080, function(){
//`this` is the underlying http.Server powering the connect app
console.log( 'App is listening on port ' + this.address().port )
})
来自source code连接:
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
关于javascript - 从 Node JS connect.js 获取服务器的端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29781855/