How to Capture Output of Child Process in Node.js Easily
In Node.js, you can capture the output of a child process by using the
child_process module's spawn or exec functions and listening to the stdout stream or callback. The stdout event provides the output data, which you can collect and use in your program.Syntax
Node.js provides two main ways to run child processes and capture their output: spawn and exec. spawn returns a stream for output, while exec buffers the output and returns it in a callback.
- spawn(command, args, options): Runs a command with arguments and returns a ChildProcess object. You listen to
stdoutandstderrstreams to get output. - exec(command, options, callback): Runs a command and buffers all output. The callback receives
error,stdout, andstderr.
javascript
import { spawn, exec } from 'child_process'; // Using spawn const child1 = spawn('command', ['arg1', 'arg2']); child1.stdout.on('data', (data) => { console.log(`Output: ${data}`); }); // Using exec exec('command arg1 arg2', (error, stdout, stderr) => { if (error) { console.error(`Error: ${error.message}`); return; } console.log(`Output: ${stdout}`); });
Example
This example runs the ls command (lists files) using spawn and captures its output by listening to the stdout stream. It prints the list of files in the current directory.
javascript
import { spawn } from 'child_process'; const ls = spawn('ls', ['-lh', '.']); let output = ''; ls.stdout.on('data', (data) => { output += data.toString(); }); ls.stderr.on('data', (data) => { console.error(`Error: ${data}`); }); ls.on('close', (code) => { console.log(`Child process exited with code ${code}`); console.log('Output captured:\n' + output); });
Output
Child process exited with code 0
Output captured:
(total size and list of files in current directory)
Common Pitfalls
Common mistakes when capturing child process output include:
- Not listening to
stdoutorstderrstreams, so no output is captured. - Assuming output is a string without converting from Buffer.
- Using
spawnwhen you want buffered output, orexecfor large output which can cause memory issues. - Not handling errors from the child process.
javascript
import { spawn } from 'child_process'; // Wrong: Not listening to stdout const child = spawn('ls'); // No output captured here // Right: Listen to stdout and convert Buffer to string child.stdout.on('data', (data) => { console.log(data.toString()); });
Quick Reference
| Method | Description | Output Type | Use Case |
|---|---|---|---|
| spawn(command, args) | Runs command with args, returns streams | Streams (stdout, stderr) | When you want to process output as it comes |
| exec(command, callback) | Runs command, buffers output | Buffered string output | When output is small and you want all at once |
Key Takeaways
Use
spawn to capture output as streams for large or continuous data.Use
exec to capture buffered output for small commands.Always listen to
stdout and convert Buffer to string to read output.Handle errors by listening to
stderr or checking the callback error.Avoid buffering large output with
exec to prevent memory issues.