使用NodeJS设置环境变量 [英] Setting environment variable with NodeJS

查看:1002
本文介绍了使用NodeJS设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从Node设置环境变量(当前使用 v8.9.3

I need to set an environment variable from Node (currently using v8.9.3)

理想情况下,我希望在程序启动时运行 export DATA_DIR = / var / lib / data

Ideally, I would like to run export DATA_DIR=/var/lib/data when the program starts.

1 。尝试生成一个 child_process 进行设置,但它出现无效。

1. Tried spawning a child_process to set this, but it does not appear to work.

示例:

const { spawnSync } = require( 'child_process' );
spawnSync( 'export', [ 'DATA_DIR=/var/lib/data' ] );

但这会导致 ENOENT

Error: spawnSync export ENOENT...
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawnSync export',
path: 'export',
spawnargs: [ 'DATA_DIR=/var/lib/data' ]

2。。尝试设置 process.env.DATA_DIR ='/ var / lib / data' ,但此似乎是对于节点进程而言是本地的,不会被其他人识别。

2. Tried setting process.env.DATA_DIR = '/var/lib/data' but this appears to be local to the node process and is not recognized by others.

3 。尝试过npm模块: dotenv envs 环境 tiny-envs ,它们主要用于加载环境变量。

3. Tried npm modules: dotenv, envs, environmental, and tiny-envs and these are primarily for loading envrionment variables.

请先谢谢您。

推荐答案

您不能为不是当前进程后代的进程设置环境变量。在Linux下,不存在系统环境变量之类的东西。

You can't set an environment variable for processes that are not descendants of the current process. And under Linux, there is no such thing as system environment variable.

export 不是独立的命令,而是一个shell内置函数,用于设置当前shell进程的环境变量,以及设置后的子进程。就像您打开终端的两个选项卡,然后从该选项卡中的 export 值使用其他选项卡中的值。

export is not a standalone command but a shell builtin that sets the environment variable for the current shell process and its children forked after it is set. Like you open two tabs of terminal and export a value from this tab and use the value from other tab.

您可以使用格式将键值保存到文件中,然后另一个进程可以读取文件以获得键值。

You can save the key, value to file with your format then another process can read the file to get a value of the key.

这篇关于使用NodeJS设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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