Performance: spawn for streaming processes
This affects how quickly data from child processes is handled and streamed without blocking the main event loop.
Jump into concepts and practice - no test required
const { spawn } = require('child_process');
const child = spawn('some-long-running-command');
child.stdout.on('data', (chunk) => {
process.stdout.write(chunk);
});
child.stderr.on('data', (chunk) => {
process.stderr.write(chunk);
});const { exec } = require('child_process');
exec('some-long-running-command', (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return;
}
console.log(stdout);
});| Pattern | Memory Usage | Event Loop Blocking | Responsiveness | Verdict |
|---|---|---|---|---|
| exec with callback | High (buffers full output) | Blocks until process ends | Low (waits for full output) | [X] Bad |
| spawn with streaming | Low (streams chunks) | Non-blocking | High (processes data as it arrives) | [OK] Good |
spawn in Node.js for running commands compared to exec?spawn behaviorspawn runs commands and streams their output as it happens, without waiting for the whole output to finish.execexec buffers the entire output before returning it, which can cause delays or memory issues with large outputs.spawn from the child_process module in Node.js?require and destructuring to import specific functions.const { spawn } = require('child_process'); to get spawn from the module.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?stdout data events to print output live, stderr for errors, and close to know when the process ends.spawn streams output, so the console logs will show file list lines as they come, errors if any, and finally the exit code.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}`);
});data event provides a Buffer, so logging it directly prints a Buffer object, not a readable string.data.toString() before logging.spawn is best to process each JSON line as it arrives without waiting for the command to finish?stdout 'data' event with bufferingexec buffers all output (bad for long-running), close fires only at end, and reading from file is indirect and slower.