Home > database >  Can I read .env into a variable instead of into process.env?
Can I read .env into a variable instead of into process.env?

Time:06-22

I would like to read the contents of my .env file into a variable other than process.env in Node.js. I am currently using the dotenv library but I am willing to use something else if anyone has alternatives to offer.

In my particular .env, username and password pairs will be stored on the server-side for authentication. I would like to read the file contents without overwriting process.env because there are other parts of my application that depend on values not being overwritten. I know that override: false is set by default in dotenv, so the values won't be overwritten, but I still need to access the new values. An example is USERNAME being set in one file to 'xterm' for a third-party terminal login, but if a user's username in the dotenv file is 'USERNAME' then I need to authenticate their password against the value instead of against 'xterm', if that makes sense.

If I could aggregate the data from my .env file to something like process.env.specialValues and access the information via that nested property, that would be perfect.

Example of desired end behavior for clarity: process.env.specialValues.USERNAME

CodePudding user response:

Use the parse() method to load the data into a variable

const { readFileSync } = require("fs");
const { resolve } = require("path");
const { parse } = require("dotenv");

const env = parse(readFileSync(resolve(process.cwd(), ".env")));

or if you're using ES modules

import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { parse } from "dotenv";

const env = parse(readFileSync(resolve(process.cwd(), ".env")));
  • Related