How to resolve a path that includes an environment variable, in nodejs?

You can use a regex to replace your variable with the relevant property of process.env :

let str = '%LOCALAPPDATA%\\Google\\Chrome\\Application'
let replaced = str.replace(/%([^%]+)%/g, (_,n) => process.env[n])

I don't think a package is needed when it's a one-liner.


Here is a generic helper function for this:

/**
 * Replaces all environment variables with their actual value.
 * Keeps intact non-environment variables using '%'
 * @param  {string} filePath The input file path with percents
 * @return {string}          The resolved file path
 */
function resolveWindowsEnvironmentVariables (filePath) {
  if (!filePath || typeof(filePath) !== 'string') {
    return '';
  }

  /**
   * @param  {string} withPercents    '%USERNAME%'
   * @param  {string} withoutPercents 'USERNAME'
   * @return {string}
   */
  function replaceEnvironmentVariable (withPercents, withoutPercents) {
    let found = process.env[withoutPercents];
    // 'C:\Users\%USERNAME%\Desktop\%asdf%' => 'C:\Users\bob\Desktop\%asdf%'
    return found || withPercents;
  }

  // 'C:\Users\%USERNAME%\Desktop\%PROCESSOR_ARCHITECTURE%' => 'C:\Users\bob\Desktop\AMD64'
  filePath = filePath.replace(/%([^%]+)%/g, replaceEnvironmentVariable);

  return filePath;
}
  • Can be called from anywhere
  • Does basic type checking first, you may want to change what is returned by default in the first if block
  • Functions are named in ways that explain what they do
  • Variables are named in ways that explain what they are
  • Comments added make it clear what outcomes can occur
  • Handles non-environment variables wrapped in percents, since the Windows file system allows for folders to be named %asdf%
  • JSDoc blocks for automated documentation, type checking, and auto-complete in certain editors
  • You may also want to use if (process.platform !== 'win32') {} depending on your need

Adding a TypeScript friendly addition to the excellent answer by Denys Séguret:

let replaced = str.replace(/%([^%]+)%/g, (original, matched) => {
      const r = Process.env[matched]
      return r ? r : ''
})

I realize that the question is asking for Windows environment variables, but I modified @Denys Séguret's answer to handle bash's ${MY_VAR} and $MY_VAR style formats as I thought it might be useful for others who came here.

Note: the two arguments are because there are two groupings based on the variations of the format.

str.replace(/\$([A-Z_]+[A-Z0-9_]*)|\${([A-Z0-9_]*)}/ig, (_, a, b) => process.env[a || b])