Environment Variables (.env) का उपयोग
एक .env file settings और secrets को आपके code और git से बाहर रखती है।
In this page:
Syntax
# .env
KEY=value
// app.js
require('dotenv').config();
const value = process.env.KEY;
Environment Variables (.env)
dotenv package .env से KEY=value lines start-up पर process.env में load करता है। Node 20.6 और बाद वाला इसे node --env-file=.env से load कर सकता है। .gitignore में .env add करें और सिर्फ names list करने वाला एक .env.example commit करें।
Note:
कभी real secrets वाला .env commit न करें।
उदाहरण: Environment variables (.env)
function parseEnv(text) {
const out = {};
for (const line of text.split("\n")) {
const m = line.match(/^\s*([A-Z_]+)\s*=\s*(.*)\s*$/);
if (m) out[m[1]] = m[2];
}
return out;
}
const env = parseEnv("PORT=3000\nDB_HOST=localhost\n");
console.log(env, typeof env.PORT, Number(env.PORT) + 1);
// Output:
// { PORT: '3000', DB_HOST: 'localhost' } string 3001
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- secrets commit करना
- variables पढ़ने से पहले dotenv load करना भूल जाना
- यह मान लेना कि values numbers हैं
चैप्टर सारांश
- .env configuration hold करता है
- dotenv या --env-file इसे load करते हैं
- Values strings हैं
- इसे git से बाहर रखें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: