Chapter 19. Managing Node
The Node ecosystem reaches far and wide, from running scripts on a laptop to managing data on remote servers. The diversity of Node’s core functionality, combined with the thousands of user-created modules, provides a rich environment for accomplishing nearly any programming task. However, this diversity can also present a challenge in navigating the options for accomplishing common tasks. This chapter demonstrates some of the common issues that Node developers may face.
Using Environment Variables
Problem
Your Node application requires different values in different environments, such as on your local machine and in production.
Solution
Use environment variables to set and read values in different environments. The core Node module process contains an env property, which will provide your application with access to any environment variables. In the following example, I am reading an environment variable named NODE_ENV:
process.env.NODE_ENV
To set an environment variable, you can specify a value ahead of running the node command to start the application. The following will set the NODE_ENV value to development and run the index.js script:
$NODE_ENV=developmentnodeindex.js
When working with projects with multiple environment variables, it is typically preferable to store those values locally in an .env file. Doing so in Node requires the dotenv package, which can be instaled from npm:
$npminstalldotenv--save
Now in your application code, require ...