Spawn NodeJS child processes to run expensive Unix commands

JS
S
JavaScript

Simple example of Spawning Child Processes (2 childs spawned with an OS level command) with their STDIO Streams piped together. * Notes regarding data flows: child.stdin(W), child.stdout(R), and child.stderr(W). On the stdin (W), readable streams of data can be piped into the stdin writable.

1const { spawn } = require('child_process');
2
3const unix_find = spawn('find', ['.', '-type', 'f']);
4const unix_wc = spawn('wc', ['-l']); // -lines only
5
6// Pipe Find stdout into WordCount stdin
7unix_find.stdout.pipe(unix_wc.stdin);
8
9// stdin Streams Access
10unix_find.stdout.on('data',(data) => {
11    console.log(`unix find stdout:\n${data}`);
12});
13
14unix_wc.stdout.on('data', (data) => {
15    // Output from the OS command passed when spawning the child process
16    console.log(`child stdout:\n${data}`);
17});
18
19unix_wc.stderr.on('data', (data) => {
20    console.error(`child stderr:\n${data}`);
21});

Created on 7/31/2017