runCommands.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { spawn, ChildProcess, SpawnOptions } from "node:child_process";
  2. export function spawnCommand(
  3. command: string,
  4. args: string[] = [],
  5. options?: SpawnOptions
  6. ): ChildProcess {
  7. return spawn(command, args, { ...options });
  8. }
  9. export async function hasCommand(command: string): Promise<boolean> {
  10. try {
  11. await waitForCommand(spawnCommand("which", [command], { stdio: "ignore" }));
  12. return true;
  13. } catch {
  14. return false;
  15. }
  16. }
  17. export async function waitForCommand(child: ChildProcess): Promise<number> {
  18. return new Promise((resolve, reject) => {
  19. child.on("close", (code) => {
  20. if (code !== 0) {
  21. const message = `$(${child}) exited with code ${code}`;
  22. reject(new Error(message));
  23. } else {
  24. resolve(code);
  25. }
  26. });
  27. });
  28. }
  29. export async function readStdout(child: ChildProcess): Promise<string[]> {
  30. const stdout: string[] = [];
  31. return new Promise((resolve) => {
  32. child.stdout?.on("data", (data) => {
  33. stdout.push(data.toString());
  34. });
  35. child.on("close", () => resolve(stdout));
  36. });
  37. }