Performance: dotenv for environment configuration
dotenv affects the initial loading time of a Node.js application by reading environment variables from a file before the app starts.
Jump into concepts and practice - no test required
// Call dotenv.config() once at the app entry point
require('dotenv').config();
// Other modules access process.env directlyrequire('dotenv').config(); // Called multiple times in different modules
| Pattern | File Reads | Startup Delay | Runtime Impact | Verdict |
|---|---|---|---|---|
| Multiple dotenv.config() calls | Multiple reads | Increases by 10-20ms per call | None | [X] Bad |
| Single dotenv.config() call at entry | One read | Minimal (~10ms) | None | [OK] Good |
dotenv in a Node.js project?dotenv reads a file (usually .env) and loads variables into process.env.process.env -> Option Crequire('dotenv').config() at the start of your app..env file, what will be the output?// .env file content
API_KEY=12345
PORT=8080require('dotenv').config();
console.log(process.env.API_KEY);
console.log(process.env.PORT);require('dotenv').config(), process.env.API_KEY is set to "12345" and process.env.PORT is set to "8080" as strings.const dotenv = require('dotenv');
dotenv.config;
console.log(process.env.SECRET_KEY);dotenv.config; without parentheses, so the function is not executed.config(), environment variables are not loaded into process.env, so SECRET_KEY remains undefined..env file has NODE_ENV=development and API_URL=http://localhost:3000. You also have a .env.production file with NODE_ENV=production and API_URL=https://api.example.com. How can you load the correct file based on the environment?path option to specify which file to load.require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` }), you load .env.development or .env.production based on the environment.