41

I am fairly new to node.js, and have a program that I have to set an environment variable in order to run (using the noble library, my bash command is: sudo NOBLE_HCI_DEVICE_ID=x node program.js, to tell my code which Bluetooth adapter - HCI device - to use).

The reason behind this is that I have a number of modules, each needing their own Bluetooth adapter, and I wish to specify in my code which adapter each module should use.

I've found lots of articles telling me how to consume environment variables in my code and set them via the command line (process.env.VARIABLE_NAME), but nothing telling me how to set them from within node.js.

Is it possible to set the environment variables in my node.js code?

Seanny123
  • 8,776
  • 13
  • 68
  • 124
Alex
  • 1,082
  • 3
  • 12
  • 23

3 Answers3

72

You can not only consume environment variables in node with process.env but also set them. This will set the variable within your current node process and any child processes it calls, but not the calling shell itself.

// consume
var alreadySetEnvVarForDevice = process.env.NOBLE_HCI_DEVICE_ID

// set
process.env['NOBLE_HCI_DEVICE_ID'] = 1
M. Adam Kendall
  • 1,202
  • 9
  • 8
  • 6
    or you can just do: `process.env.NOBLE_HCI_DEVICE_ID = 1` – Kien Pham Sep 07 '18 at 08:10
  • 6
    I came here with the same question, but this answer isn't good enough for me. I need to use node to set environment variables that will (1) be visible to other process beyond node, and (2) outlive the node process. – Tom Aug 02 '19 at 18:37
  • 2
    My needs are the same as @Tom. I would like to set the env within Node, as an init function. Then when I exit node, and run it again, it will be in the environment for reading back for use. – Ric Mar 22 '20 at 23:39
  • 4
    It turns out it's not possible, and for reasons that seem good. – Tom Mar 29 '20 at 16:01
  • This should probably be placed at the top of the file node access first like your /bin/www.js or your server.js. Otherwise some files might not have access to it if they run before node reaches this. – Dashiell Rose Bark-Huss Jul 08 '22 at 01:52
-8

If you are using express, you can set the variables as follow:

var express = require('express');
var app = express();

// set the environment mode, default is process.env.NODE_ENV
app.set('env','development');

app.get('env');
// => 'development' 
tony.0919
  • 1,145
  • 5
  • 16
  • 27
-9

run command like following in command prompt

export FOREVER_ROOT=/var/log/

Here export set a environment variable

OR

Execute "/etc/environment" in every shell where you want the variables to be updated:

$ /etc/environment

Dineshaws
  • 2,065
  • 16
  • 26