我想运行一个可执行文件,它的路径包含一个环境变量,例如,如果我想运行chrome.exe,我想写这样的东西
var spawn = require('child_process').spawn;
spawn('chrome',[], {cwd: '%LOCALAPPDATA%\\Google\\Chrome\\Application', env: process.env})
而不是
var spawn = require('child_process').spawn;
spawn('chrome',[], {cwd: 'C:\\Users\myuser\\AppData\\Local\\Google\\Chrome\\Application', env: process.env}).
我是否可以使用包来实现这一目标?
答案 0 :(得分:12)
您可以使用正则表达式将变量替换为process.env
的相关属性:
let str = '%LOCALAPPDATA%\\Google\\Chrome\\Application'
let replaced = str.replace(/%([^%]+)%/g, (_,n) => process.env[n])
我不认为当它是一个单行时需要一个包。
答案 1 :(得分:0)
在Linux / MacOS上,我产生了一个使用env变量解析路径的过程,这是安全的-让bash为您完成工作。显然性能较低,但功能更强大。看起来像这样:
import * as cp from 'child_process';
// mapPaths takes an array of paths/strings with env vars, and expands each one
export const mapPaths = (searchRoots: Array<string>, cb: Function) => {
const mappedRoots = searchRoots.map(function (v) {
return `echo "${v}"`;
});
const k = cp.spawn('bash');
k.stdin.end(mappedRoots.join(';'));
const results: Array<string> = [];
k.stderr.pipe(process.stderr);
k.stdout.on('data', (d: string) => {
results.push(d);
});
k.once('error', (e) => {
log.error(e.stack || e);
cb(e);
});
k.once('exit', code => {
const pths = results.map((d) => {
return String(d || '').trim();
})
.filter(Boolean);
cb(code, pths);
});
};
答案 2 :(得分:0)
为DenysSéguret的出色答案添加了TypeScript友好的补充:
let replaced = str.replace(/%([^%]+)%/g, (original, matched) => {
const r = Process.env[matched]
return r ? r : ''
})
答案 3 :(得分:0)
这是一个通用的辅助功能:
/**
* 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;
}
if
块中默认返回的内容%asdf%
if (process.platform !== 'win32') {}
答案 4 :(得分:0)
我意识到问题是在询问Windows环境变量,但我修改了@DenysSéguret的答案以处理bash的li { line-height:1rem;}
和<li style="line-height:1rem" > </li>
样式格式,因为我认为这对来到这里的其他人可能有用
注意:这两个参数是因为根据格式的不同有两个分组。
${MY_VAR}