YulePale
YulePale

Reputation: 7706

What does normalizePort() function do in Nodejs?

I was going through this answer then I saw this line of code:

var port = normalizePort(process.env.PORT || '4300');

Why not

var port = (process.env.PORT || '4300');

From this blog there is an explanation that:

The normalizePort(val) function simply normalizes a port into a number, string, or false.

I still don't get it. I then check out what normalizing is here. I have some idea but I still don't understand.

What is the purpose of the normalizePort() function?

What would happen if we don't use it?

(An example of what it does would really help me understand) Thank you.

Upvotes: 12

Views: 11176

Answers (4)

aitchkhan
aitchkhan

Reputation: 1952

normalizePort function was introduced in the express-generator which was a boilerplate from the Express team.

From the generator code:

/**
 * Normalize a port into a number, string, or false.
 */
function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

Explanation: This function is a safety railguard to make sure the port provided is number, if not a number then a string and if anything else set it to false.

You really don't need normalizePort function if you are providing the port yourself to the environment variable and ensuring that the port is going to be a number always via some sort of config, which is the answer to your question:

Why not

var port = (process.env.PORT || '4300');

Upvotes: 18

Sathiraumesh
Sathiraumesh

Reputation: 6117

enter image description here

I think this will help read this section of the page

https://brianflove.com/2016/03/29/typescript-express-node-js/

Upvotes: 0

Mark
Mark

Reputation: 92440

Here's what normalizePort() does:

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

You basically want your port to be a number not a string in most cases. But there are instances when you might want to pass a non-numeric string, such as a named pipe, socket, etc. This simply turns strings that parse to numbers into numbers and leaves regular strings alone.

Upvotes: 2

Nick
Nick

Reputation: 749

From the source of Express Generator:

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}
  1. Executes parseInt, that essentially converts the value to an integer, if possible.
  2. Checks if the value is not-a-number.
  3. Checks if is a valid port value.

If you're the one providing the values on the code, there's no need for the function.

Upvotes: 2

Related Questions