summaryrefslogtreecommitdiff
path: root/app/lib/pipe.js
blob: db58e5f8f27981c470a2ee76ff3e21f06b2db4ec (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
import { spawn } from "node:child_process";

export default 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();
  });
}