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