I'd like to output a message like "Listening on port {port_#}" to the terminal from my node js server.
I found documentation, such as this, NodeJS: How to get the server's port?, but they only talk about Express JS.
I'm using the ConnectJS aspect to connect. So my code looks like:
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080);
console.log("Listening on port %d", connect.address().port);
This, however, does not work. How would I log the port to terminal?
You are trying to call the .address()
method of the connect library. This method does not exist. It does not even exist on an instance of connect()
. The method you are looking for lives in the http.Server
object.
When you create a connect instance, an app is returned. When you tell the app to listen, you can provide a callback which get called when the app begins to listen. This callback gets called with the http.Server
as the context bound to 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 )
})
From the source code for connect:
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};