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.
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');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With