简体   繁体   中英

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?

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

在此处输入图片说明

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

Ie

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM