Beginner LevelNode JS
Compare child_process methods: exec, execFile, spawn, and fork.
❓ Interview Prompt: Compare child_process functions: exec (buffered shell), execFile (binary without shell), spawn (streaming data), and fork (V8 Node child IPC).
The 'node:child_process' module spawns parallel OS processes:
•
'exec()': Spawns a shell ('/bin/sh'), buffering stdout/stderr up to a maxBuffer size (vulnerable to shell injection!).
•
'execFile()': Invokes an executable binary directly without a shell.
•
'spawn()': Streams stdout/stderr data via Readable Streams (ideal for long-running CLI tools).
•
'fork()': Special variant of 'spawn()' that spawns a new V8 Node.js process with a built-in IPC channel ('process.send()').
Code Implementation Example
javascript
import { spawn, fork } from 'node:child_process';
// Stream long-running process stdout
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => console.log('stdout: ${data}'));
// Fork a child Node.js script with IPC communication
const child = fork('worker.js');
child.send({ task: 'START' });💡Spawning streaming sub-processes and forking Node.js child processes.
🎯 Interview Key Takeaway
Use spawn() for streaming large process output, and fork() for communication between Node.js processes via IPC.
#child_process#spawn#fork#exec#Beginner
Back to all Node JS Questions→