File size: 1,356 Bytes
03b405b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const { spawn } = require("node:child_process");
const { logger } = require("../monitoring/logger");

function run(command, args = [], options = {}) {
  return new Promise((resolve, reject) => {
    const child = spawn(command, args, {
      windowsHide: true,
      shell: false,
      ...options
    });
    let stdout = "";
    let stderr = "";
    const timeoutMs = options.timeoutMs || 0;
    const timer = timeoutMs > 0
      ? setTimeout(() => {
          child.kill("SIGTERM");
          reject(new Error(`Command timed out after ${timeoutMs}ms: ${command}`));
        }, timeoutMs)
      : null;

    child.stdout?.on("data", (chunk) => {
      stdout += chunk.toString();
      options.onStdout?.(chunk.toString());
    });
    child.stderr?.on("data", (chunk) => {
      stderr += chunk.toString();
      options.onStderr?.(chunk.toString());
    });
    child.on("error", reject);
    child.on("close", (code) => {
      if (timer) clearTimeout(timer);
      if (code === 0) return resolve({ stdout, stderr, code });
      const error = new Error(`Command failed (${code}): ${command} ${args.join(" ")}`);
      error.stdout = stdout;
      error.stderr = stderr;
      error.code = code;
      logger.warn({ command, args, code, stderr: stderr.slice(-1000) }, "Command failed");
      reject(error);
    });
  });
}

module.exports = { run };