Understanding and creating own (dotenv) module in nodejs
Importance
I don't think there's any developer who is unaware of the importance of storing confidential information like api_keys or any secret key in a (.env) file.
- Most developers store secret information in a (.env) file which they can access from any file of that project.
Can modify secret information from one place and its change is reflected in all places.
The usual way of using environment variables
- Almost all NodeJS developers utilize the power of environment variables in their projects by installing dotenv library.
npm install dotenv
- Create a .env file in root of the project.
SECRET=secretvalue
Import dotenv module in the main file. (let's say index.js)
require('dotenv').config();
Now you can load any the environment variables stored in .env file with
command:
console.log(process.env.SECRET)
Understanding theory about environmental variables
Environment variables are dynamic variables used by program/OS for configuration. They are mostly set outside of the program at the OS level. In Windows, you can set it using the environment variables setting and providing the unique name of the variable and its path to the bin folder.
After this, it is accessible from anywhere in the system.
It tells our computer system that when I type or use that unique name I need the computer to provide me access to that specific tool/program.
Understanding and accessing environmental variables in nodejs
In NodeJS we can access environment variables with a global 'process' object available in core NodeJS.
'process' is a global object that holds information about the current NodeJS instance and every bit of information about the computer system and it can also control the current NodeJS process.
console.log(process)
If you execute this code in NodeJs, you will get a process object with various information. You can try this on your own.
You can also find env as a key of a 'process' object whereas 'env' itself is an object containing various environment variables with keys and values.
When dotenv library is used it first reads .env file and writes the values as an object to process.env object.
Now we can access the stored environment variables from any file till the NodeJS process is alive.
Note: This variable stored using NodeJS is removed after NodeJS process is killed.
Creating own mini dotenv module
- Initialize NodeJS project. Set all options as default.
npm init
Create any file where you want to store environment variables.
Let's create .envScratch file at root of the project.
// this is .envScratch file at root of the project.
SECRETKEY=SECRETVALUE
Create any .js file where you will be writing code for mini dotenv module.
Example: main.js
// main.js file where you will be writing code for mini dotenv module.
const fs = require("fs");
const path = require("path");
// load the file name .envScratch in main.js as we are storing environment variable at file .envScratch
function loadEnv() {
const envFilePath = path.join(__dirname, ".envScratch");
if (fs.existsSync(envFilePath)) {
// this will read all file content from .envScratch file.
const content = fs.readFileSync(envFilePath, "utf-8");
// spilt content from .envScratch based on newline and returns value as an array
const envVariables = content.split("\n").map((line) => line.trim());
// now set extracted variables as node env variables.
// as envVariables is array of content splited based on new line
// forEach method is used here.
envVariables.forEach((item) => {
// Again split values based on "=" and destructure array to store
// respective value as key and value pair.
const [key, value] = item.split("=");
// update process.env object with additional
// key and value pair.
process.env[key.trim()] = value.trim();
// Now the key and values are stored at environment variable at
// OS level and is accessible till this nodejs process is alive.
});
}
}
// export loadEnv function so that it can be executed at main file
// of current project.
module.exports = loadEnv;
- Create main js file. Let us assume index.js is the main file that is executed first when the program is loaded.
// import loadEnv function from main.js
const loadEnv = require("./main.js");
// ececute loadEnv function.
loadEnv();
// now you can read and access enviroment variable till this
// nodejs process is alive.
console.log(process.env.SECRETKEY);
- In this way, any NodeJS developer can know the inner workings of environment variables as well can create their mini prototype of dotenv library.
Subscribe to my newsletter
Read articles from Gaurab Khanal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by