Last active
May 4, 2021 14:14
-
-
Save leandrocrs/3cb79633ec823d3d336bda9bc2f6f9aa to your computer and use it in GitHub Desktop.
Promisefy child_process spawn in typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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