How can I set process.env from main process inside of an NPM package?

Viewed 180

I am writing an NPM package that sets environment variables using process.env. Here is the code from the NPM package:

Object.keys(parsedObj).forEach((key) => {
  process.env[key] = parsedObj[key];
});

In this file within the package I console.log process.env and see the variables set correctly. However, when I call this function in my code that imports this function, I console.log process.env and the variables are missing.

For context, here is the entire file: https://github.com/arsood/Cooler-Env/blob/master/loadEnv.js#L33

Does anyone have thoughts as to why these global variables are not available in the main code after running this function? Do modules run their own process? If so, is there a way to write environment variables to the main process from the package?

1 Answers

Looks like your function is async and your module exports the function so I would advice you to import the file once in the file when your start your app, and call it and wait for its execution and only then start the rest of your app, otherwise there is no warranty because the code is async.

loadEnv()
     .then(() => {
          initApp(); // Some function that starts rest of the app.
     })
Related