Created
June 20, 2023 15:36
-
-
Save RBFraphael/dcd3385c8e18a885345d364cff0f3e2f to your computer and use it in GitHub Desktop.
envvar NodeJS helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { exec } = require("child_process"); | |
const appPath = process.env.PATH.split(";").filter((segment) => segment.trim().length > 0).filter((segment) => segment.indexOf("node_modules") > -1); | |
export function getVar(variable, callback){ | |
exec(`echo %${variable}%`, (err, stdOut, stdErr) => { | |
if(err == null){ | |
if(callback){ | |
callback(stdOut); | |
} | |
} | |
}); | |
} | |
export function setVar(variable, value, callback){ | |
exec(`setx ${variable} "${value}"`, (err, stdOut, stdErr) => { | |
if(err == null){ | |
if(callback){ | |
callback(stdOut); | |
} | |
} else { | |
if(callback){ | |
callback(false); | |
} | |
} | |
}); | |
} | |
export function removeVar(variable, callback){ | |
exec(`reg delete HKCU\\Environment /F /V ${variable}`, (err, stdOut, stdErr) => { | |
if(err == null){ | |
if(callback){ | |
callback(stdOut); | |
} | |
} | |
}); | |
} | |
export function getPath(callback){ | |
exec(`echo %PATH%`, (err, stdOut, stdErr) => { | |
let data = stdOut.trim(); | |
let pathArray = data.split(";").filter((segment) => segment.trim().length > 0); | |
let uniquePathArray = []; | |
pathArray.forEach((path) => { | |
if(uniquePathArray.indexOf(path) == -1 && appPath.indexOf(path) == -1){ | |
uniquePathArray.push(path); | |
} | |
}); | |
if(callback){ | |
callback(uniquePathArray); | |
} | |
}); | |
} | |
export function setPath(pathArray, callback){ | |
let systemPath = pathArray.join(";"); | |
let envPath = [...appPath, ...pathArray].join(";"); | |
process.env.PATH = envPath; | |
exec(`setx PATH "${systemPath}"`, (err, stdOut, stdErr) => { | |
if(err == null){ | |
if(callback){ | |
callback(stdOut); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment