Setting environment variable with NodeJS

孤人 提交于 2019-12-11 18:08:16

问题


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

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

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

Example:

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

But this results with an ENOENT:

Error: spawnSync export ENOENT...
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawnSync export',
path: 'export',
spawnargs: [ '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. Tried npm modules: dotenv, envs, environmental, and tiny-envs and these are primarily for loading envrionment variables.

Thank you in advance.


回答1:


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 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.



来源:https://stackoverflow.com/questions/47841094/setting-environment-variable-with-nodejs

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