Categories
JavaScript Answers

How to get the server’s port with JavaScript and Express?

Spread the love

Sometimes, we want to get the server’s port with JavaScript and Express.

In this article, we’ll look at how to get the server’s port with JavaScript and Express.

How to get the server’s port with JavaScript and Express?

To get the server’s port with JavaScript and Express, we can use the listener.address method.

For instance, we write

const app = require("express")();
//...
const listener = app.listen(8888, () => {
  console.log("Listening on port ", listener.address().port);
});

to call app.listen with the port to listen to.

And then we call listener.address and use the returned object’s port property to get the port being listened to.

Conclusion

To get the server’s port with JavaScript and Express, we can use the listener.address method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *