Skip to content

Instantly share code, notes, and snippets.

@sefgit
Created March 7, 2025 13:13
Show Gist options
  • Save sefgit/b1ee02471b54730d41ce66187190b331 to your computer and use it in GitHub Desktop.
Save sefgit/b1ee02471b54730d41ce66187190b331 to your computer and use it in GitHub Desktop.
node async subprocess
//
// https://kisaragi-hiu.com/nodejs-cmd/
//
const { spawn } = require("child_process");
const process = require("process");
function cmd(...command) {
let p = spawn(command[0], command.slice(1));
return new Promise((resolveFunc) => {
p.stdout.on("data", (x) => {
process.stdout.write(x.toString());
});
p.stderr.on("data", (x) => {
process.stderr.write(x.toString());
});
p.on("exit", (code) => {
resolveFunc(code);
});
});
}
async function main() {
await cmd("bash", "-c", "echo one; sleep 1; echo two; sleep 1");
console.log("This must happen last.");
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment