Created
June 5, 2024 18:23
-
-
Save prmichaelsen/ce18ecd65f20d00190afb8184c1805bd to your computer and use it in GitHub Desktop.
example single command terminal exec using streams
This file contains 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 { 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