问题
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