We use spawn to run other programs from Node.js and handle their output as it happens, like watching a live stream.
spawn for streaming processes in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
const { spawn } = require('child_process');
const child = spawn(command, args, options);
child.stdout.on('data', (data) => {
// handle output data chunk
});
child.stderr.on('data', (data) => {
// handle error output chunk
});
child.on('close', (code) => {
// process finished with exit code
});command is the program you want to run, like 'ls' or 'ping'.
args is an array of strings with arguments for the command.
ls -lh /usr command and prints its output as it comes.const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`Output: ${data}`);
});ping to send 4 packets and prints each response as it arrives.const { spawn } = require('child_process');
const ping = spawn('ping', ['-c', '4', 'google.com']);
ping.stdout.on('data', (data) => {
console.log(`Ping output: ${data}`);
});This program runs node -v to get the Node.js version installed. It prints the version as soon as it receives it, handles any errors, and shows when the process ends.
const { spawn } = require('child_process');
// Run 'node -v' to get Node.js version
const child = spawn('node', ['-v']);
child.stdout.on('data', (data) => {
console.log(`Node version: ${data.toString()}`);
});
child.stderr.on('data', (data) => {
console.error(`Error: ${data.toString()}`);
});
child.on('close', (code) => {
console.log(`Process exited with code ${code}`);
});Use streams: spawn lets you read output as a stream, so you don't wait for the whole process to finish.
Handle errors: Always listen to stderr to catch errors from the spawned process.
Close event: The close event tells you when the process ends and its exit code.
spawn runs commands and streams their output live.
It is useful for handling big or ongoing outputs without delay.
Always listen to stdout, stderr, and close events.
Practice
spawn in Node.js for running commands compared to exec?Solution
Step 1: Understand
spawnbehaviorspawnruns commands and streams their output as it happens, without waiting for the whole output to finish.Step 2: Compare with
execexecbuffers the entire output before returning it, which can cause delays or memory issues with large outputs.Final Answer:
It streams output live without buffering all data first. -> Option CQuick Check:
spawn streams output live = B [OK]
- Thinking spawn retries commands automatically
- Assuming spawn hides output
- Believing spawn formats output as JSON
spawn from the child_process module in Node.js?Solution
Step 1: Identify Node.js import syntax
Node.js commonly uses CommonJS syntax withrequireand destructuring to import specific functions.Step 2: Check correct destructuring
The correct way isconst { spawn } = require('child_process');to getspawnfrom the module.Final Answer:
const { spawn } = require('child_process'); -> Option DQuick Check:
Destructure spawn from require('child_process') = C [OK]
- Using default import syntax in CommonJS
- Not destructuring spawn from the module
- Using import without enabling ES modules
const { spawn } = require('child_process');
const ls = spawn('ls', ['-l']);
ls.stdout.on('data', (data) => {
console.log(`Output: ${data}`);
});
ls.stderr.on('data', (data) => {
console.error(`Error: ${data}`);
});
ls.on('close', (code) => {
console.log(`Process exited with code ${code}`);
});
What will this code do when run in a directory?Solution
Step 1: Analyze event listeners
The code listens tostdoutdata events to print output live,stderrfor errors, andcloseto know when the process ends.Step 2: Understand spawn behavior
spawnstreams output, so the console logs will show file list lines as they come, errors if any, and finally the exit code.Final Answer:
Print the detailed list of files, errors if any, and exit code when done. -> Option AQuick Check:
spawn streams output and errors live = D [OK]
- Thinking output is buffered until process ends
- Ignoring stderr event handling
- Assuming event names are incorrect
spawn?
const { spawn } = require('child_process');
const proc = spawn('node', ['-v']);
proc.stdout.on('data', (data) => {
console.log(data);
});
proc.on('close', (code) => {
console.log(`Exited with ${code}`);
});Solution
Step 1: Check stdout data handling
Thedataevent provides a Buffer, so logging it directly prints a Buffer object, not a readable string.Step 2: Correct usage to convert Buffer
To print readable output, convert Buffer to string usingdata.toString()before logging.Final Answer:
It logs a Buffer object instead of a string for stdout data. -> Option BQuick Check:
stdout data is Buffer, needs toString() = A [OK]
- Logging Buffer directly without conversion
- Ignoring error event handling (not critical here)
- Confusing 'close' and 'exit' events
spawn is best to process each JSON line as it arrives without waiting for the command to finish?Solution
Step 1: Understand streaming JSON lines
For continuous JSON lines, you must process output as it streams, not wait for all output.Step 2: Use
Listen to 'data' events, accumulate chunks, split by newline, and parse each JSON line immediately to handle streaming data.stdout'data' event with bufferingStep 3: Why other options fail
execbuffers all output (bad for long-running),closefires only at end, and reading from file is indirect and slower.Final Answer:
Listen to stdout 'data' events, buffer chunks, split by newline, and parse each JSON line immediately. -> Option AQuick Check:
Stream and parse JSON lines live = A [OK]
- Using exec for streaming output
- Parsing only after process ends
- Ignoring buffering and splitting lines
