Paz
Paz

Reputation: 1099

How to append values to the PATH environment variable in NodeJS?

Following the answer suggested in the question -

Is it possible to permanently set environment variables?

I was able to set new environment variables permanently with the command -

spawnSync('setx', ['-m', 'MyDownloads', 'H:\\temp\\downloads'])

But now my goal is to append new values to the PATH environment variable.

Is it possible?

Upvotes: 9

Views: 3959

Answers (3)

mherzog
mherzog

Reputation: 1230

I don't have rights to modify my registry, and I also would rather not call an OS command such as setx.

The following adds an additional component to the Windows PATH. I then ran Selenium, which uses the new setting.

// Display current value of PATH
const current_value = process.env.PATH;
console.log("PREV VALUE:")
console.log(current_value)

// Add the additional entry
const addl_entry = String.raw`\my\new\path\component`
process.env["PATH"] = addl_entry + ";" + current_value

// Display the new value
console.log("NEW VALUE:")
console.log(process.env.PATH)

Upvotes: 0

hong4rc
hong4rc

Reputation: 4113

Run your script with the admin permission:

  • Open cmd or PowerShell with admin
  • Run node your_script.js
  • To append PATH variable, you can set value is : %PATH%;your_new_value here (%PATH% get old value)

If you run with electron app, you should require admin permission.

Don't forget setx run on window

enter image description here

Upvotes: 2

marksy_91
marksy_91

Reputation: 226

Why don't you just get the environment variable and then append to it?

I.e.

const {spawnSync} = require("child_process");
const current_value = process.env.PATH;
const new_path_value = current_value.concat(";", "/some/new/path");

var result = spawnSync('setx', ['-m', 'PATH', new_path_value])

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

Update "/some/new/path" and run this as admin as the link you provided suggests and it should work.

Upvotes: 5

Related Questions