feat: add exec function

Signed-off-by: Alfi Maulana <alfi.maulana.f@gmail.com>
This commit is contained in:
Alfi Maulana 2024-11-21 22:04:45 +07:00
parent 5dcae6263b
commit d91c238854
No known key found for this signature in database
GPG Key ID: 2242A64C2A8DF5A4
2 changed files with 39 additions and 0 deletions

13
src/exec.test.ts Normal file
View File

@ -0,0 +1,13 @@
import { exec } from "./exec.js";
describe("execute commands", () => {
it("should successfully execute a command", async () => {
await exec("node", ["--version"]);
});
it("should fail to execute a command", async () => {
await expect(exec("node", ["--invalid"])).rejects.toThrow(
"Command exited with status code 9",
);
});
});

26
src/exec.ts Normal file
View File

@ -0,0 +1,26 @@
import { spawn } from "node:child_process";
/**
* Executes a command with the given arguments.
*
* The command is executed with `stdin` ignored and both `stdout` and `stderr` inherited by the parent process.
*
* @param command The command to execute.
* @param args The arguments to pass to the command.
* @returns A promise that resolves when the command exits successfully or rejects if it exits with a non-zero status code or encounters an error.
*/
export async function exec(command: string, args: string[]): Promise<void> {
return new Promise<void>((resolve, reject) => {
const proc = spawn(command, args, {
stdio: ["ignore", "inherit", "inherit"],
});
proc.on("error", reject);
proc.on("close", (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`Command exited with status code ${code}`));
}
});
});
}