1

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

So for example, if I set the DATA_DIR for GeoServer, then start GeoServer from the same process, it should recognize the data directory variable I just set?
@iSkore no, it not working. If you "start" GeoServer then os is going to create a new process id and a new session for GeoServer process. I suggest use PM2 as a process manager, PM2 api allow pass environment variables to context of new process pm2.keymetrics.io/docs/usage/pm2-api pm2.keymetrics.io/docs/usage/application-declaration
Yes, I use PM2 to start GeoServer - I was trying to keep the question a little more generic to node running on a linux environment. But, I suppose this will lean more towards GeoServer's "on start" operation and linux. So if I spin up the pid with PM2, set the ENV in my PM2 start command, GeoServer should interpret that as a typical environment variable? Not too familiar with running thing other than node apps with PM2.
@iSkore Pm2 is ok for my example gist.github.com/hoangsetup/3b2101ec0befef0f5b38b25c4b69b1d6 server.js is going to start child process app.js thus app.js can use env process.env.DATA_DIR export form the server.js (process.env.DATA_DIR = '/var/lib/data';)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.