Alex75
Alex75

Reputation: 517

Node.js - load .env file from a different location

I have a Node.js application which runs fine with the standard node index.js syntax (relative path...) Then I had the need to run it with the absolute path in node /home/bots/mybot/index.js and it was working great as well.

Now I have the need to add a .env file which is still running great from relative path, but I'm not able to run it from absolute path anymore since it's not reading the .env file! I think it is looking for it in the / path which is not ideal of course.

EDIT: I'm currently using discord.js library which probably is using dotenv or something very similar inside.

Any suggestions?

Upvotes: 5

Views: 5777

Answers (1)

Ashutosh Kumar
Ashutosh Kumar

Reputation: 907

Taking an assumption in my mind, i.e. you're using dotenv package for the .env

From the Docs (You can specify the custom path to .env)

You may specify a custom path if your file containing environment variables is located elsewhere.

require('dotenv').config({ path: '/full/custom/path/to/your/env/vars' })

Or you may do it using the command line, when calling your index.js

While running node your/absolute/path/index.js

node -r dotenv/config your/absolute/path/index.js dotenv_config_path=/custom/path/to/your/env/vars

Upvotes: 8

Related Questions