Mastering node env file for Seamless Environment Variable Management in Node.js

Introduction to node-env-file

Environment variables are crucial in Node.js for configuring different environments without changing code. The node-env-file module makes managing these variables easy and seamless.

Installing node-env-file

npm install node-env-file --save

Loading Environment Variables

To load environment variables from a .env file, you can use:


 const env = require('node-env-file');
 env(__dirname + '/.env');

Reading Environment Variables

Once loaded, you can access the variables using process.env:


 console.log(process.env.YOUR_VARIABLE_NAME);

Specifying Encoding

You can specify the encoding of your .env file:


 env(__dirname + '/.env', { encoding: 'utf8' });

Parsing Multiple Files

Load and merge multiple .env files:


 env(__dirname + '/.env');
 env(__dirname + '/.env.local');

API Examples

Example .env File


 DB_HOST=localhost
 DB_USER=root
 DB_PASS=s1mpl3

Accessing DB Configuration


 const env = require('node-env-file');
 env(__dirname + '/.env');

 const dbHost = process.env.DB_HOST;
 const dbUser = process.env.DB_USER;
 const dbPass = process.env.DB_PASS;

 console.log(`Database Host: ${dbHost}`);
 console.log(`Database User: ${dbUser}`);
 console.log(`Database Pass: ${dbPass}`);

Application Example Using node-env-file

Setting Up the App

Follow these steps to set up a simple Node.js app with environment variables:

1. Create a .env file:


 PORT=3000
 SECRET_KEY=mysecretkey

2. Create a server.js file:


 const env = require('node-env-file');
 const http = require('http');

 env(__dirname + '/.env');

 const port = process.env.PORT || 3000;
 const secretKey = process.env.SECRET_KEY || 'defaultkey';

 const requestHandler = (req, res) => {
   res.end(`Your secret key is: ${secretKey}`);
 };

 const server = http.createServer(requestHandler);

 server.listen(port, (err) => {
   if (err) {
     return console.log('something bad happened', err);
   }

   console.log(`server is listening on ${port}`);
 });

By following the steps above, you can easily manage environment variables in a Node.js application using node-env-file.

Hash: 298db019e87de85385ac101c6b14406b06aefeff88b9b1fd793a058d87d97b24

Leave a Reply

Your email address will not be published. Required fields are marked *