Initial commit
[yaffs-website] / node_modules / exec-buffer / index.js
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
9 const fsP = pify(fs);
10 const rmP = pify(rimraf);
11 const input = Symbol('inputPath');
12 const output = Symbol('outputPath');
13
14 module.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 = tempfile();
30         const 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
44 module.exports.input = input;
45 module.exports.output = output;