Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to permanently set environment variables?

Tags:

node.js

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?

like image 519
user3715648 Avatar asked Feb 28 '17 21:02

user3715648


2 Answers

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.

like image 99
Brad Christie Avatar answered Sep 24 '22 16:09

Brad Christie


Write a file named setEnv.js and paste the following code in that.

Save file somewhere in your system, eg. in D:\Codes\JS.

step 1

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}`)
}

step 2

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.

Before

enter image description here

After

enter image description here

References

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

like image 42
hygull Avatar answered Sep 22 '22 16:09

hygull