December 18, 2018
This is not going to be a deep dive into Node’s environmental variables, but rather a quick look at how you may use environmental variables. I wanted to test load balancing an application. This meant I needed a way to dynamically set the port my server would listen on. This, it turns out, is a great example of how to use environmental variables provisioned from the command line. These can then be referenced from within the app to set variables - in my case
In my server file,
index.js, I defined my port as:
const port = process.argv || 8081. This says that if I fail to pass an explicit port, I will use the default 8081. However, I can also pass in a variable after node (process.argv), the file node is running (process.argv) and it will be mapped to my port variable.
# In one terminal window $ node server/index.js 8082 listening on port 8082 # In a different terminal window $ node server/index.js 8083 listening on port 8083
This is a simple use case. It was also one of the first use cases I came across that helped me see how the process arguments worked in Node.js.
Thanks for reading! My name's Stephen Weiss. I live in Chicago with my wife, Kate, and dog, Finn.
Click here to see the archives of my weeks in review and sign up yourself!