Languages
[Edit]
EN

Node.js - read .env file (custom solution)

10 points
Created by:
Gigadude
791

In this short article, we would like to show some custom implementaion that lets to read environment variables from .env file under Node.js.

 

The below implementation provides the following API:

Constants:

ENV_PATH: string;

property that contains default env file name (.env).

Functions:

readVariables(path: string, constants: Record<string, () => string>): Record<string, string>;

function that reads .env file variables and returns them as object.

ArgumentDescription
path

path to .env file (optional)

constants

key -> function map that lets to inject prefefined variables in .env file (optional)

e.g.

Example index.js file:

Example .env file:

Where:

  • $VARIABLE_NAME_1$ and $VARIABLE_NAME_2$ allow access to local variables defined in .env file,
  • %CONSTANT_NAME% allows access to pre-defined constant in application source code,
  • *HOME* allows access to pre-defined variable in process.env object.

Example output:

Resultobject that contains read environment variables (key -> value map)

initializeVariables(path: string, constants: Record<string, () => string>): void;

function that reads .env file variables and sets them in process.env object (key -> value map).

ArgumentDescription
pathpath to .env file (optional)
constants

key -> function map that lets to inject prefefined variables in .env file (optional)

Resultnothing

 

Practical example

Edit

Project structure:

 

Example index.js file:

Note:

When you use __dirname or __filename in ENV_CONSTANTS be sure what values are returned. It is recommended to create ENV_CONSTANTS object and read .env file in index.js file in the project root directory.

Example output:

 

Example .env file:

 

Example env.js file:

 

Alternative titles

  1. Node.js - use .env file (custom solution)
  2. Node.js - read environment variables from file (custom solution)
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join