summaryrefslogtreecommitdiff
path: root/app/lib/pipe.js
blob: e329b2b85578ce4249a62dcb6d1356771d042728 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"use strict";

const { spawn } = require("child_process");

module.exports = function pipe({ command, flags, stdin="", buffer } = {}) {
  return new Promise((resolve, reject) => {
    const child = spawn(command, flags);
    let stdout = (buffer?[]:"");
    let stderr = "";

    child.stderr.on("data", d => stderr += d);
    child.stdout.on("data", d => (buffer?
      stdout.push(d):stdout+=d));

    child.on("close", code => {
      const res = { code, stderr, stdout:
        (buffer?Buffer.concat(stdout):stdout) };

      if (code) reject(res);
      else resolve(res);
    });

    //child.stdin.setEncoding("utf-8");
    child.stdin.write(stdin);
    child.stdin.end();
  });
}