我想从我的节点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);
然而,这不起作用。如何将端口记录到终端?
答案 0 :(得分:2)
您正在尝试调用连接库的.address()
方法。此方法不存在。它甚至不存在于connect()
的实例中。您要查找的方法位于http.Server
对象中。
创建连接实例时,会返回一个应用程序。当您告诉应用程序侦听时,您可以提供一个回调,当应用程序开始侦听时会调用该回调。使用http.Server
作为绑定到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 for connect:
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};