Node-ローカルバイナリパッケージ、ローカル依存としてシームレスに使用

1711 ワード

ローカルバイナリパッケージ
主に、異なる環境で異なるローカルバイナリファイルを使用する必要があります. 。 , .
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> {
    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']);