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

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.