Skip to content

Instantly share code, notes, and snippets.

@dikarel
Created October 17, 2019 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dikarel/b3109f64b6577765590a29ace0c3920b to your computer and use it in GitHub Desktop.
Save dikarel/b3109f64b6577765590a29ace0c3920b to your computer and use it in GitHub Desktop.
How to pipe shell commands in NodeJS
// In this example, we use ChildProcess and piping to perform the NodeJS
// version of `find ~/Documents | egrep '\.ts$'`
const ChildProcess = require(“child_process”);
// 1. Start both "find" and "egrep"
// "shell" has to be true, so that we have access to "~"
const find = ChildProcess.spawn("find", ["~/Documents"], { shell: true });
const egrep = ChildProcess.spawn("egrep", ["\\.ts$"], {
shell: true
});
// 2. Pipe the output of "find" into "egrep"'s input
find.stdout.pipe(egrep.stdin);
// 3. Once "find" has finished outputting results, we need to notify "egrep"
// that there's no more input. If we don't do this, egrep will hang forever
// waiting for the end of its input
find.stdout.once("end", () => {
egrep.stdin.end();
});
// 4. Pipe "egrep" to console output
egrep.stdout.pipe(process.stdout);
// 5. Once "egrep" finishes, we terminate our program
egrep.once("exit", exitCode => {
process.exit(exitCode === null ? undefined : exitCode);
});
// 6. If there are any errors, surface them to the user
find.on("error", err => {
throw err;
});
egrep.on("error", err => {
throw err;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment