You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. const fs = require('fs');
  3. const execa = require('execa');
  4. const pFinally = require('p-finally');
  5. const pify = require('pify');
  6. const rimraf = require('rimraf');
  7. const tempfile = require('tempfile');
  8. const fsP = pify(fs);
  9. const rmP = pify(rimraf);
  10. const input = Symbol('inputPath');
  11. const output = Symbol('outputPath');
  12. module.exports = opts => {
  13. opts = Object.assign({}, opts);
  14. if (!Buffer.isBuffer(opts.input)) {
  15. return Promise.reject(new Error('Input is required'));
  16. }
  17. if (typeof opts.bin !== 'string') {
  18. return Promise.reject(new Error('Binary is required'));
  19. }
  20. if (!Array.isArray(opts.args)) {
  21. return Promise.reject(new Error('Arguments are required'));
  22. }
  23. const inputPath = opts.inputPath || tempfile();
  24. const outputPath = opts.outputPath || tempfile();
  25. opts.args = opts.args.map(x => x === input ? inputPath : x === output ? outputPath : x);
  26. const promise = fsP.writeFile(inputPath, opts.input)
  27. .then(() => execa(opts.bin, opts.args))
  28. .then(() => fsP.readFile(outputPath));
  29. return pFinally(promise, () => Promise.all([
  30. rmP(inputPath),
  31. rmP(outputPath)
  32. ]));
  33. };
  34. module.exports.input = input;
  35. module.exports.output = output;