× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

NodeJS: How to get the server's port?

James Womack
Mar 20, 2015
<p><strong>Requiring the http module was never necessary.</strong></p> <p>An additional import of <code>http</code> is not necessary in Express 3 or 4. Assigning the result of <code>listen()</code> is enough.</p> <pre><code>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 </code></pre> <p>Again, this is tested in Express 3.5.1 &amp; 4.0.0. Importing <code>http</code> was never necessary. The listen method return an http server object. <a href="https://github.com/visionmedia/express/blob/master/lib/application.js#L531">https://github.com/visionmedia/express/blob/master/lib/application.js#L531</a></p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/4840879/NodeJS:%20How%20to%20get%20the%20server's%20port?/23075316">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus