Bird
Raised Fist0
Node.jsframework~20 mins

spawn for streaming processes in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Spawn Streaming Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Node.js spawn code?
Consider this code snippet using spawn from child_process. What will be printed to the console?
Node.js
import { spawn } from 'child_process';

const ls = spawn('ls', ['-l']);

ls.stdout.on('data', (data) => {
  console.log(`Output chunk: ${data.toString()}`);
});

ls.stderr.on('data', (data) => {
  console.error(`Error chunk: ${data.toString()}`);
});

ls.on('close', (code) => {
  console.log(`Process exited with code ${code}`);
});
AThe console prints the directory listing in chunks, then 'Process exited with code 0'.
BThe console prints nothing because spawn does not emit data events.
CThe console prints an error because 'ls' is not a valid command in Node.js.
DThe console prints 'Process exited with code 1' immediately without output.
Attempts:
2 left
💡 Hint
Think about how spawn streams output and how events are emitted.
📝 Syntax
intermediate
2:00remaining
Which option correctly spawns a process to stream output line-by-line?
You want to spawn a process and handle its output line-by-line as it streams. Which code snippet correctly sets this up?
A
const proc = spawn('ping', ['-c', '4', 'google.com']);
proc.stdout.on('data', (line) => {
  console.log(line);
});
B
const proc = spawn('ping', ['-c', '4', 'google.com']);
proc.stdout.on('line', (line) => {
  console.log(line);
});
C
const proc = spawn('ping', ['-c', '4', 'google.com']);
proc.stdout.on('data', (data) => {
  data.toString().split('\n').forEach(line => console.log(line));
});
D
const proc = spawn('ping', ['-c', '4', 'google.com']);
proc.stdout.on('chunk', (chunk) => {
  console.log(chunk.toString());
});
Attempts:
2 left
💡 Hint
Remember that 'data' events emit buffers, not lines.
🔧 Debug
advanced
2:00remaining
Why does this spawn code never print output?
This code spawns a process but never prints any output. What is the cause?
Node.js
import { spawn } from 'child_process';

const proc = spawn('node', ['-e', "console.log('hello')"]);

proc.stdout.on('data', (data) => {
  console.log(`Output: ${data}`);
});
AThe process exits before the event listener is attached, missing the output.
BThe code is correct and will print 'Output: hello' as expected.
CThe output is sent to stderr, not stdout, so 'data' event on stdout never fires.
DThe process output is buffered and not flushed, so no 'data' event fires.
Attempts:
2 left
💡 Hint
Check if the output is sent to stdout or stderr and if listeners are attached properly.
state_output
advanced
2:00remaining
What is the value of variable 'output' after this spawn code runs?
Given this code, what will be the final value of the 'output' variable after the process closes?
Node.js
import { spawn } from 'child_process';

let output = '';
const proc = spawn('echo', ['Hello World']);

proc.stdout.on('data', (data) => {
  output += data.toString();
});

proc.on('close', () => {
  console.log('Process done');
});
A'Hello World\n'
B'Hello World'
C'' (empty string)
Dundefined
Attempts:
2 left
💡 Hint
Remember what the echo command outputs including line breaks.
🧠 Conceptual
expert
2:00remaining
Which option best explains why spawn is preferred over exec for streaming large outputs?
Why do developers often choose spawn instead of exec when they want to process large output streams from child processes?
Aspawn automatically parses output into JSON, while exec returns raw strings.
Bspawn can only run shell commands, while exec can run any executable.
Cspawn runs processes asynchronously, but exec runs them synchronously blocking the event loop.
Dspawn streams output data in chunks, avoiding buffer size limits, while exec buffers all output in memory before returning.
Attempts:
2 left
💡 Hint
Think about memory usage and how output is handled in both methods.

Practice

(1/5)
1. What is the main advantage of using spawn in Node.js for running commands compared to exec?
easy
A. It automatically retries failed commands.
B. It runs commands only in the background without output.
C. It streams output live without buffering all data first.
D. It converts output to JSON format automatically.

Solution

  1. Step 1: Understand spawn behavior

    spawn runs commands and streams their output as it happens, without waiting for the whole output to finish.
  2. Step 2: Compare with exec

    exec buffers the entire output before returning it, which can cause delays or memory issues with large outputs.
  3. Final Answer:

    It streams output live without buffering all data first. -> Option C
  4. Quick Check:

    spawn streams output live = B [OK]
Hint: spawn streams output live, exec buffers all output [OK]
Common Mistakes:
  • Thinking spawn retries commands automatically
  • Assuming spawn hides output
  • Believing spawn formats output as JSON
2. Which of the following is the correct way to import spawn from the child_process module in Node.js?
easy
A. const spawn = require('child_process').spawn;
B. import spawn from 'child_process';
C. import { spawn } from 'child_process';
D. const { spawn } = require('child_process');

Solution

  1. Step 1: Identify Node.js import syntax

    Node.js commonly uses CommonJS syntax with require and destructuring to import specific functions.
  2. Step 2: Check correct destructuring

    The correct way is const { spawn } = require('child_process'); to get spawn from the module.
  3. Final Answer:

    const { spawn } = require('child_process'); -> Option D
  4. Quick Check:

    Destructure spawn from require('child_process') = C [OK]
Hint: Use destructuring with require for spawn import [OK]
Common Mistakes:
  • Using default import syntax in CommonJS
  • Not destructuring spawn from the module
  • Using import without enabling ES modules
3. Consider this code snippet:
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?
medium
A. Print the detailed list of files, errors if any, and exit code when done.
B. Only print errors and ignore normal output.
C. Buffer all output and print it after the process ends.
D. Throw a syntax error because of wrong event names.

Solution

  1. Step 1: Analyze event listeners

    The code listens to stdout data events to print output live, stderr for errors, and close to know when the process ends.
  2. Step 2: Understand spawn behavior

    spawn streams output, so the console logs will show file list lines as they come, errors if any, and finally the exit code.
  3. Final Answer:

    Print the detailed list of files, errors if any, and exit code when done. -> Option A
  4. Quick Check:

    spawn streams output and errors live = D [OK]
Hint: spawn streams stdout, stderr, and close events [OK]
Common Mistakes:
  • Thinking output is buffered until process ends
  • Ignoring stderr event handling
  • Assuming event names are incorrect
4. What is wrong with this code snippet that uses 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}`);
});
medium
A. It misses listening to the 'error' event on the process.
B. It logs a Buffer object instead of a string for stdout data.
C. It uses wrong arguments for spawn command.
D. It does not handle the 'exit' event.

Solution

  1. Step 1: Check stdout data handling

    The data event provides a Buffer, so logging it directly prints a Buffer object, not a readable string.
  2. Step 2: Correct usage to convert Buffer

    To print readable output, convert Buffer to string using data.toString() before logging.
  3. Final Answer:

    It logs a Buffer object instead of a string for stdout data. -> Option B
  4. Quick Check:

    stdout data is Buffer, needs toString() = A [OK]
Hint: Convert stdout Buffer to string before logging [OK]
Common Mistakes:
  • Logging Buffer directly without conversion
  • Ignoring error event handling (not critical here)
  • Confusing 'close' and 'exit' events
5. You want to run a long-running command that outputs JSON lines continuously. Which approach using spawn is best to process each JSON line as it arrives without waiting for the command to finish?
hard
A. Listen to stdout 'data' events, buffer chunks, split by newline, and parse each JSON line immediately.
B. Use exec to get all output at once, then parse JSON lines after process ends.
C. Listen only to close event and parse output then.
D. Spawn the process without event listeners and read output from a file.

Solution

  1. Step 1: Understand streaming JSON lines

    For continuous JSON lines, you must process output as it streams, not wait for all output.
  2. Step 2: Use stdout 'data' event with buffering

    Listen to 'data' events, accumulate chunks, split by newline, and parse each JSON line immediately to handle streaming data.
  3. Step 3: Why other options fail

    exec buffers all output (bad for long-running), close fires only at end, and reading from file is indirect and slower.
  4. Final Answer:

    Listen to stdout 'data' events, buffer chunks, split by newline, and parse each JSON line immediately. -> Option A
  5. Quick Check:

    Stream and parse JSON lines live = A [OK]
Hint: Buffer and split stdout data by newline to parse JSON live [OK]
Common Mistakes:
  • Using exec for streaming output
  • Parsing only after process ends
  • Ignoring buffering and splitting lines