Skip to content

Instantly share code, notes, and snippets.

@leandrocrs
Last active May 4, 2021 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leandrocrs/3cb79633ec823d3d336bda9bc2f6f9aa to your computer and use it in GitHub Desktop.
Save leandrocrs/3cb79633ec823d3d336bda9bc2f6f9aa to your computer and use it in GitHub Desktop.
Promisefy child_process spawn in typescript
import { spawn } from "child_process";
import { SpawnOptionsWithoutStdio } from "node:child_process";
export default function spawnAsync(
cmd: string,
args: string[] = [],
options: SpawnOptionsWithoutStdio = {}
) {
return new Promise<number>((resolve, reject) => {
const result = spawn(cmd, args, options);
if (result.stdout) {
result.stdout.on("data", (data) => {
process.stdout.write(data);
});
}
if (result.stderr) {
result.stderr.on("data", (data) => {
process.stderr.write(data);
});
}
result.on("close", (code) => {
console.log(`child process exited with code ${code}`);
if (code !== 0) {
reject(code);
}
resolve(code);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment