Node.js - how to set environment variables in code

I'm new enough to node.js, and there is a program that I have to set environment variables to run (using noble , my bash command: sudo NOBLE_HCI_DEVICE_ID=x node program.js to tell my code that uses the Bluetooth adapter HCI device )

The reason for this is that I have several modules, each of which needs its own Bluetooth adapter, and I want to indicate in my code which adapter each module should use.

I found many articles telling me how to consume environment variables in my code and set them using the command line (process.env.VARIABLE_NAME), but didn’t tell me how to set them in node.js,

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

thanks

+5
source share
3 answers

You can not only use environment variables in node with process.env , but also set them. This sets the variable in the current node process, and any child processes that it invokes, but not the invoking shell itself.

 // consume var alreadySetEnvVarForDevice = process.env.NOBLE_HCI_DEVICE_ID // set process.env['NOBLE_HCI_DEVICE_ID'] = 1 
+15
source

execute the command as shown on the command line

 export FOREVER_ROOT=/var/log/ 

Here export set environment variable

OR

Run "/ etc / environment" in each shell where you want the variables to be updated:

$ / etc / environment

-2
source

If you use express, you can set the following variables:

 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' 
-2
source

All Articles