本地二进制文件包装器
次要是为了解决,不同环境下须要应用不同的本地二进制文件。
为什么不依据以后环境在线下载呢?
因为网络下载会有墙和编译的等不可抗力问题。所以自行下载好放起来, 再通过包装器应用.
const path = require('path');
const fs = require('fs-extra');
class Local_Bin_Wrapper {constructor(){this.map = new Map();
}
/**
* 配置包门路
* @param url 本地二进制包的绝对路径
* @param platfrom 包的平台 darwin -> macOs win32-> windows
* @returns this
*/
src(url: string, platfrom: "darwin" | "win32"): this {this.map.set(platfrom, path.resolve(url));
return this;
}
// 返回合乎以后平台的二进制地址
path(): string {return this.map.get(process.platform);
}
// 仅仅提供一个调用办法
async run(cmd = ["--version"]): Promise<execa.ExecaChildProcess<string>> {const path = this.path();
try {
// 验证是否存在
// 如果不存在就会报错 try catch 捕捉
fs.statSync(path);
const result_1 = await execa(path, cmd);
console.log("command:", result_1.command);
if (result_1.stderr.length > 0) {console.log(result_1.stderr);
}
if (result_1.stdout.length > 0) {console.log(result_1.stdout);
}
return result_1;
} catch (e) {console.log(`Failed to access file ${path}`, e);
return Promise.reject(e);
}
}
}
调用例子
import * as execa from "execa";
const url = path.resolve(__dirname,'../bin');
const bin = new Local_Bin_Wrapper()
.src(`${url}/mac/pngquant/pngquant`, 'darwin')
.src(`${url}/win/pngquant/pngquant.exe`, 'win32');
// 这样便于本人封装
const pngquantBin = bin.path();
execa(pngquantBin, ['--version']);