InterviewHubPRO
Section Overview
Q32

Question 32 of 60

Part 3: Streams, Buffers & Core Modules (21 - 35)

53%
Node.js & Libuv•Part 3: Streams, Buffers & Core Modules (21 - 35)

`child_process.exec` vs `execFile` vs `spawn` vs `fork`.

In Simple Words:

  • exec(): Spawns a shell and buffers full output in memory. Vulnerable to shell command injection attacks.
  • execFile(): Invokes an executable directly without a shell. Safer.
  • spawn(): Streams process stdout/stderr in chunks; ideal for long-running processes.
  • fork(): Special spawn() dedicated to spawning Node.js scripts with built-in IPC communication channels.
javascript
const { spawn } = require('child_process');

// Streaming output from shell command:
const child = spawn('ls', ['-la']);
child.stdout.on('data', (chunk) => console.log(`Output: ${chunk}`));