user3715648
user3715648

Reputation: 1588

Is it possible to permanently set environment variables?

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?

Upvotes: 7

Views: 5720

Answers (3)

Kalebe Samuel
Kalebe Samuel

Reputation: 141

I use a generic script for mac and windows like this:

#!/bin/node

const { exec } = require("child_process");
const currentOs = require("./getOs");

const os = currentOs();

//==========================================================================
function changeMinNodeVersion() {
    console.log("\nChanging yargs min node version...");

    const minNodeVersion = String(process.versions.node).split('.')[0];
    const yargsVariable = `YARGS_MIN_NODE_VERSION=${minNodeVersion}`;
    const command = `${os === 'darwin' ? `export ${yargsVariable}` : `set ${yargsVariable}`}`;

    console.log(`Excecuting ${command}`);
    
    exec(command, (error, stdout, stderr) => {
        if (error) {
            console.log(`\nFailed to change min node version: ${error.message}`);
            return;
        }
        if (stderr) {
            console.log(`\nFailed to change min node version: ${stderr}`);
            return;
        }

        console.log(`\nVersion changed to ${minNodeVersion}`);
    });
}

//=========================================================================
changeMinNodeVersion();

So i just run using:

node ./scriptName.js

Upvotes: 0

hygull
hygull

Reputation: 8740

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

Upvotes: 3

Brad Christie
Brad Christie

Reputation: 101594

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.

Upvotes: 5

Related Questions