Reputation: 161
I've a need to know the server host name and port on which the express app in another javascript file say under lib. How can I get it?
I tried to do module.exports = app but it didn't work.
Upvotes: 0
Views: 2824
Reputation: 140
When declaring an express app, you can export a listener which will give you the host and address:
/index.js
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send('Hello world!\n');
});
var listener = app.listen(process.env.PORT || 3000);
module.exports = listener;
Then you can require
that module in your lib files to be able to access the host and port:
/lib/index.js
var listener = require('./../index.js');
var address = listener.address();
var host = address.address;
var port = address.port;
console.log('Listening on ' + host + ':' + port);
// < - 'Listening on :::3000'
Upvotes: 1