DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Stephen Charles Weiss
Stephen Charles Weiss

Posted on • Originally published at stephencharlesweiss.com on

Node Environmental Variables: A Simple Example

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 port.

Example: Running multiple instances of the same app on multiple ports

In my server file, index.js, I defined my port as: const port = process.argv[2] || 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[0]), the file node is running (process.argv[1]) and it will be mapped to my port variable.

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.

Additional Resources

Top comments (0)

We are hiring! Do you want to be our Senior Platform Engineer? Are you capable of chipping in across sysadmin, ops, and site reliability work, while supporting the open source stack that runs DEV and other communities?

This role might just be for you!

Apply now