Search code examples
node.jsnpmintellij-ideaenvironment

Unable to Access process.env Variables When Running "Current File" in IntelliJ for Model Files


I am encountering an issue with accessing process.env variables in my Node.js application's model files when running "current file" in IntelliJ. Strangely, I am able to access these variables without any issues when running "current file" on app.js.

I have tried setting the environment variables in my system's environment variables as well as in a .env file in the root directory of my project. I have also checked that the variables are being set correctly by logging them to the console in app.js.

I am using Node.js version 16 and the dotenv package to load my environment variables. I have also tried using cross-env to set the variables in my package.json file, but the issue still persists.

I suspect that the issue may be related to how process.env variables are being loaded or initialized in my application. However, I am not sure where to begin troubleshooting.

Can anyone please suggest a solution or provide guidance on how to resolve this issue when running "current file" in IntelliJ for my model files? Thank you in advance.


Solution

  • For your sample project, right-click in the file, Modify Run Configuration.

    Set Working directory to the root project directory (where .env file is located).

    Set JavaScript file to the location of the file you want to run relative to the working directory.

    run config

    Now it works:

    works