Skip to content

Instantly share code, notes, and snippets.

@prmichaelsen
Created June 5, 2024 18:23
Show Gist options
  • Save prmichaelsen/ce18ecd65f20d00190afb8184c1805bd to your computer and use it in GitHub Desktop.
Save prmichaelsen/ce18ecd65f20d00190afb8184c1805bd to your computer and use it in GitHub Desktop.
example single command terminal exec using streams
import { Readable, Writable } from "node:stream";
import { spawn } from "node:child_process";
export const execCommand = async (cmd: string) => {
const ps = spawn("sh", { env: process.env });
const data: string[] = [];
const outputStream = new Writable({
write(chunk, encoding, callback) {
data.push(chunk.toString(encoding));
callback();
},
});
ps.stdout?.pipe(outputStream);
ps.stderr?.pipe(outputStream);
const inputStream = new Readable({
async read() {
this.push(cmd);
this.push(null);
this.push("exit");
},
});
inputStream.pipe(ps.stdin);
await new Promise<string>((resolve) =>
ps.on("close", () => resolve(data.join("\n")))
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment