本地二進(jìn)制文件包裝器
主要是為了解決蛉腌,不同環(huán)境下需要使用不同的本地二進(jìn)制文件。
為什么不根據(jù)當(dāng)前環(huán)境在線下載呢只厘?
因?yàn)榫W(wǎng)絡(luò)下載會(huì)有墻和編譯的等不可抗力問(wèn)題烙丛。所以自行下載好放起來(lái),再通過(guò)包裝器使用.
const path = require('path');
const fs = require('fs-extra');
class Local_Bin_Wrapper {
constructor(){
this.map = new Map();
}
/**
* 配置包路徑
* @param url 本地二進(jìn)制包的絕對(duì)路徑
* @param platfrom 包的平臺(tái) darwin -> macOs win32-> windows
* @returns this
*/
src(url: string, platfrom: "darwin" | "win32"): this {
this.map.set(platfrom, path.resolve(url));
return this;
}
//返回符合當(dāng)前平臺(tái)的二進(jìn)制地址
path(): string {
return this.map.get(process.platform);
}
//僅僅提供一個(gè)調(diào)用方法
async run(cmd = ["--version"]): Promise<execa.ExecaChildProcess<string>> {
const path = this.path();
try {
//驗(yàn)證是否存在
//如果不存在就會(huì)報(bào)錯(cuò) 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);
}
}
}
調(diào)用例子
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']);