DEV Community

Stephen Charles Weiss
Stephen Charles Weiss

Posted on • Originally published at stephencharlesweiss.com on

1 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post