Node.js - 如何在代码中设置环境变量 [英] Node.js - how to set environment variables in code

查看:123
本文介绍了Node.js - 如何在代码中设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对node.js相当新,并且有一个程序我必须设置一个环境变量才能运行(使用贵族库,我的bash命令是: sudo NOBLE_HCI_DEVICE_ID = x node program.js ,告诉我的代码哪个蓝牙适配器--HCI设备 - 使用)。

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.

我发现很多文章告诉我如何在我的代码中使用环境变量并通过命令行设置它们(process.env.VARIABLE_NAME),但没有任何说法我如何从node.js中设置它们。

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.

是否可以在我的node.js代码中设置环境变量?

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

推荐答案

您不仅可以使用 process.env 在节点中使用环境变量,还可以设置它们。这将设置当前节点进程中的变量以及它调用的任何子进程,而不是调用shell本身。

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

这篇关于Node.js - 如何在代码中设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆