skip to Main Content

Is process.env a generic environment variable or is it NodeJs specific?

https://nodejs.org/dist/latest-v8.x/docs/api/process.html#process_process_env
They have shown how to set it with node command:
$ node -e 'process.env.foo = "bar"' && echo $foo

Is it possible to set it on terminal without node command?

2

Answers


  1. If you set an environment variable in your shell, that environment variable will be available in your Node scripts. How you set environment variables differs with different shells, but assuming you’ve set the variable in your shell, it will be available in Node.

    In bash, you could set it via export or just assigning it directly before the Node command.

    foo=bar node your_script.js
    

    or

    export foo=bar
    node your_script.js
    

    If you’re on Windows and you’re using cmd, you can use set:

    set foo=bar && node your_script.js
    

    It is also popular to use dotenv – it will pick up environment variables from your .env file contained in the root of your project.

    Assigning anything to process.env inside your Node script will not be reflected in your shell.

    Login or Signup to reply.
  2. In fact, process.env is specific to Node.js. It is an object representing the user’s environment (A collection of environment variables available to the Node.js process). When you are running a Node.js application, process.env gives you access to these variables.

    In your example, process.env.foo = "bar" sets an environment variable within the context of that Node.js script. This assignment is local to the Node.js process, so when you try to echo $foo in the sell it won’t show the value set in the Node.js script, because the shell’s environment hasn’t been modified.

    To set an environment variable directly in the terminal (outside of Node.js), you can use shell commands (the syntax may vary depending on the shell you are using); for example, in most Unix base systems (like Linux and macOS), you can set/create an environment variable like below:

    export foo="bar"
    

    After setting it like this, echo $foo will give you out the bar (which is a value of foo) in the same terminal session. This change is temporary and only affects the current terminal session unless added to shell initialization.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search