Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like to run an executable and its path contains an enviroment variable, for example if I would like to run chrome.exe I would like to write something like this

var spawn = require('child_process').spawn;
spawn('chrome',[], {cwd: '%LOCALAPPDATA%\\Google\\Chrome\\Application', env: process.env})

instead of

var spawn = require('child_process').spawn;
spawn('chrome',[], {cwd: 'C:\\Users\myuser\\AppData\\Local\\Google\\Chrome\\Application', env: process.env}).

Is there a package I can use in order to achieve this?

like image 696
Pablo Retyk Avatar asked Jan 26 '14 13:01

Pablo Retyk


2 Answers

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.

like image 102
Denys Séguret Avatar answered Sep 29 '22 01:09

Denys Séguret


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])
like image 35
duckbrain Avatar answered Sep 29 '22 02:09

duckbrain