Sometimes things change in different environments. For one, I wear a tie to church but try not to otherwise. In Node, you might want variables to change per environment. And it turns out people have wanted this exact thing, creating marvels of code for us to use as we please. Enter, nconf.
Nconf provides “hierarchical node.js configuration with files, environment variables, command-line arguments, and atomic object merging.” It is a great little package provided by the folks at NodeJitsu.
To install, run a little:
Environment Variables in Node
Often, NodeJs environments are specified through the aptly-named environment variables. These are the variables that are set on a system level, available to yours and other applications. In Unixy environments, you’d set one with:
And it turns out that
NODE_ENV is the single most-used environment variable of them all. Really, it’s the big kahuna that triggers other environment variables or code for activation.
For instance, in an Express app, you’ll see this a lot:
1 2 3
Actually, you see
configure(), but it’s all just sugar around a check to
Set NODE_ENV and Start Node
If you want to start node and set the environment variable all in a one liner, try:
Multiple, Variable Sources
You could just grab all your variables out the process environment, but the cool thing that nconf gives you is a hierarchy. The docs give the probable example of the following hierarchy:
- Command-line arguments
- Environment variables
- A file
One could access these sources in code with this beaut:
1 2 3 4 5 6
You could even have a config file specific to each environment that ships with your app and load it with a slightly spiffier:
1 2 3 4 5 6
Using the Data
Finally, after loading, just access your environment variables and incorporate them in your code as you will:
Declare some variables per environment. Likely candidates are database connection strings or web service endpoints or feature flags. These will help you avoid as many nasty if-else branches in your code.