Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Share process.env variable between multiple node js files

I have two node js files and one bat file. In the first js file, I am setting a few environment variables and in another js file, I want to access it. However, after setting variables, I am unable to find these variables in another file.
Example,

file1.js

process.env.dev_url=example.com

file2.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

console.log(process.env.user); // This returns correct value as xyz@gmail.com
console.log(process.env.dev_url); // returns undefined.

runner.bat

ECHO on
SET user=xyz@gmail.com
node file1.js
node file2.js

After running runner.bat, I can get the value of the variable user in file2, but not the other ones set in file1.js, what could be the reason, and how can I get these values in file2?

>Solution :

I don’t think env variables should be set using the method you have done in file1.js, you are only supposed to be reading them in javascript files, you can however set them using your .bat file:

ECHO on
SET user=xyz@gmail.com
SET dev_url=example.com
node file2.js

another possible solution if you need to do it using file1.js, would be importing it in file2.js

# file1.js
process.env.dev_url="example.com"

# file2.js
require('./file1.js')
console.log(process.env.user); 
console.log(process.env.dev_url); 

# runner.bat
ECHO on
SET user=xyz@gmail.com
node file2.js

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading