soumyadeep.eth
soumyadeep.eth

Reputation: 11

Not able to read values from .env file

//accessToken.mjs
import * as dotenv from "dotenv";
dotenv.config();
import { Web3Storage } from "web3.storage";

function getAccessToken() {
  // WEB3STORAGE_TOKEN environment variable before you run your code.
  console.log(process.env.WEB3STORAGE_TOKEN);
  return process.env.WEB3STORAGE_TOKEN;
}
getAccessToken();
function makeStorageClient() {
  return new Web3Storage({ token: getAccessToken() });
}
export default makeStorageClient;

running the command below

$ node .\accessToken.mjs
undefined

I added a .env file in the root directory and didn't use any quote or semicolon. I am still not able to get the WEB3STORAGE_TOKEN value.

Upvotes: 0

Views: 268

Answers (2)

soumyadeep.eth
soumyadeep.eth

Reputation: 11

Actually the file in which I called the environment variable is inside another directory and my .env file was in the root. So defining config({path:"/some/.env"}) path solves my problem

Upvotes: 0

iftikharyk
iftikharyk

Reputation: 959

Updated:

I don't know how you are working with other files but if you want to use import statements in NodeJs you need to add type attribute inside package.json like so:

"type": "module"

and in your code file use import like this

import * as dotenv from 'dotenv';
dotenv.config();
console.log(process.env.TEST);

You can see here in demo


Just put this on the top

require("dotenv").config()

Instead of

import * as dotenv from "dotenv";
dotenv.config();

Upvotes: 1

Related Questions