12

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.

YulePale
  • 6,688
  • 16
  • 46
  • 95

4 Answers4

18

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');

maazadeeb
  • 5,922
  • 2
  • 27
  • 40
aitchkhan
  • 1,842
  • 1
  • 18
  • 38
2

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.

Nick
  • 729
  • 8
  • 18
2

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.

Mark
  • 90,562
  • 7
  • 108
  • 148
0

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/

Sathiraumesh
  • 5,949
  • 1
  • 12
  • 11