Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 843
Paz Avatar asked Jan 02 '20 07:01

Paz


2 Answers

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.

like image 157
marksy_91 Avatar answered Oct 09 '22 03:10

marksy_91


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

like image 25
hong4rc Avatar answered Oct 09 '22 03:10

hong4rc