Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - how to set environment variables in code

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?

like image 762
Alex Avatar asked Apr 10 '15 11:04

Alex


People also ask

Do I need to set environment variable for node?

You really do not need to set up your own environment to start learning Node. js. Reason is very simple, we already have set up Node.

How do I set environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.

How do you set environment as production in node JS?

You can signal Node. js that you are running in production by setting the NODE_ENV=production environment variable. in the shell, but it's better to put it in your shell configuration file (e.g. . bash_profile with the Bash shell) because otherwise the setting does not persist in case of a system restart.


Video Answer


1 Answers

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 
like image 102
M. Adam Kendall Avatar answered Sep 28 '22 10:09

M. Adam Kendall