Node.js - how to set environment variables in code

旧街凉风 提交于 2019-12-08 14:42:04

问题


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?


回答1:


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



回答2:


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' 



回答3:


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



来源:https://stackoverflow.com/questions/29560844/node-js-how-to-set-environment-variables-in-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!