What does normalizePort() function do in Nodejs?

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.


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.


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