1

I'm new here and I'm new with this programming language, so maybe my question is something very obvious.

I am trying to set an environmental variable in Node.js in Visual Studio Code (for example NODE_ENV to production). I've tried setting it using an .env file and using the dotenv package. This does not seem to work, and when I try to print the variable to the console it prints 'undefined'. This is the part that I have included in the .env file:

NODE_ENV = production 

This is a part of the js file that I try to run:

const path = require('path')
require('dotenv').config()
console.log(process.env.NODE_ENV)

When I run this 'undefined' gets printed to the console. I also tried passing the place of the file as an argument with the config for dotenv, like this. That did not work. I even tried to set te environmental variables directly via launch.json like this:

"version": "0.2.0",
    "configurations": [
        {
            "type": "pwa-node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "program": "${file}",
            "env": {
                "NODE_ENV" : "production",
            }
        }

    ]
}

That also did not work.

Why is this? Why isn't Visual Studio Code able to change the environmental variables? Thanks in advance.

1 Answers1

0

According to the docs of dotenv there should be no space between the variable name and its value.

The syntax is: VARNAME=VALUE

So your .env file should be

NODE_ENV=production
h-sifat
  • 1,455
  • 3
  • 19
  • This didn't work unfortunately. 'Undefined' still gets printed to the console. – LaucsInuhre Oct 31 '21 at 19:57
  • Hey @LaucsInuhre I've tested the answer myself before posting here! I don't know what's going on then! How about you debug your application and actually see what's going on? – h-sifat Nov 01 '21 at 00:40
  • There is something strange happening: When I use the debug console to run the program it does know what the variables are and prints them, but when I run server.js via the terminal, it says undefined. – LaucsInuhre Nov 04 '21 at 17:03
  • @LaucsInuhre Why not make a small reproducible example and put it in a git hub repo so that we can inspect it ourselves? – h-sifat Nov 05 '21 at 05:34
  • Thank you, but I already ‘solved’ it by avoiding environmental variables altogether. – LaucsInuhre Nov 08 '21 at 08:58
  • 1
    Really? Lol! You'll have to use them sooner or later anyway! May be it's just because of the `dotenv` library. Try the [config library](https://www.npmjs.com/package/config). – h-sifat Nov 08 '21 at 14:54
  • just realized that it is actually the way to do it in node js. – bugthefifth Mar 26 '23 at 19:42
  • as far as I remember. I read somewhere. .env works with Django, but does not work with node. May be it is a false memory, after realizing it, but it sits in my memory so clear :)) – bugthefifth Mar 26 '23 at 19:52