I need a way to set an environment variable permanently. I could get away with having this only work in Windows for now, but ideally i'd like a solution that is OS agnostic. From what I can tell though, Node will only set the var for the current process/children processes. Is what I want even possible?
Can probably use setx
and export
, though not sure of implications/privileges required (I would assume in windows a UAC bump would be necessary, and in linux you'd need sudo). Here's a best-guess:
var exec = require('child_process').exec;
// Add FOO to global environment with value BAR
// setEnv('FOO', 'BAR', callback)
// Append /foo/bar to PATH
// setEnv('PATH', '+=;/foo/bar', callback)
function setEnv(name, value, cb) {
if (!name) throw new Error('name required.');
if (typeof value === 'undefined') throw new Error('value required.');
var cmd;
if (value.indexOf('+=') === 0) value = process.env[name] + value.substring(2);
value = value.indexOf(' ') > -1 ? `"${value}"` : value;
switch (process.platform) {
case 'linux': cmd = `export ${name}=${value}`; break;
case 'win32': cmd = `setx ${name} ${value} /m"; break;
default: throw new Error('unsupported platform.'); break;
}
exec(cmd, cb);
}
I should mention this really isn't ideal; I recommend defining them as part of your execution task or look at using something like dotenv.
Write a file named setEnv.js and paste the following code in that.
Save file somewhere in your system, eg. in D:\Codes\JS
.
const {spawnSync} = require("child_process");
// setx -m MyDownloads H:\temp\downloads
var result = spawnSync('setx', ['-m', 'MyDownloads', 'H:\\temp\\downloads'])
// STDOUT
var stdOut = result.stdout.toString();
console.log(stdOut)
// STDERR
var stdErr = result.stderr.toString();
if(stdErr === '') {
console.log('Successfully set environment variable')
} else {
console.log(`ERROR: ${stderr}`)
}
Open console window as an administrator and type the below commands.
otherwise »
ERROR: Access to the registry path is denied.
cd D:\Codes\JS
node setEnv.js
Now, have a look at the below images, in my case.
Execute a command line binary with Node.js
SETX command: error: Access to the registry path is denied
https://www.codejava.net/java-core/how-to-set-environment-variables-for-java-using-command-line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With