If you’re working on a Node.js project that utilizes ES modules and you need to store a secret value in a .env
file, I’ll guide you on how to make it accessible in your Node.js script.
First, make sure to install the dotenv
package by running the following command in your terminal:
npm i dotenv
Once the package is installed, you can use the following code:
import * as dotenv from 'dotenv'
dotenv.config()
console.log(process.env.PASSWORD)
This code assumes that you’re using ES modules. If you’re not, don’t worry, it’s simple to add support for ES modules by including "type": "module"
in your package.json
file.
Tags: Node.js, .env files, import syntax, ES modules