node.jswindowselectronsetx

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?


Solution

  • 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.