Skip to Content
JavaScript Cookbook, 3rd Edition
book

JavaScript Cookbook, 3rd Edition

by Adam D. Scott, Matthew MacDonald, Shelley Powers
July 2021
Intermediate to advanced
535 pages
11h 55m
English
O'Reilly Media, Inc.
Content preview from JavaScript Cookbook, 3rd Edition

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=development node index.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:

$ npm install dotenv --save

Now in your application code, require ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning JavaScript, 3rd Edition

Learning JavaScript, 3rd Edition

Ethan Brown
JavaScript

JavaScript

T. J. Crowder

Publisher Resources

ISBN: 9781492055747Errata PageSupplemental Content