Advanced Node.js Interview QuestionsAdvancedConcept
Node.js · Question 71
What is the difference between spawn and exec in Node.js?
Direct answer
spawn streams stdout/stderr as data events — safe for large or long output; exec buffers entire output in memory via shell — fine for short commands but risks maxBuffer exceeded and shell injection if input is tainted.
Choosing spawn vs exec is a memory and security decision — interviews test whether you know exec runs through /bin/sh by default.
| spawn | exec | |
|---|---|---|
| Output | Streamed chunks | Buffered string (maxBuffer default 1MB) |
| Shell | No shell by default | Shell interprets command string |
| Args | Array: spawn('node', ['a.js']) | Single string: exec('node a.js') |
| Use when | Logs, compilers, tail -f | Quick git rev-parse, small stdout |
- execFile — middle ground: no shell, buffered output, explicit args.
- maxBuffer — exec throws ERR_CHILD_PROCESS_STDIO_MAXBUFFER if output too large.
- Shell injection — exec(`grep ${userInput}`) dangerous; use spawn with args array.
spawn-vs-exec.mjs
import { spawn, execFile } from "node:child_process";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
// Large output — spawn
const child = spawn("npm", ["test"], { stdio: "inherit" });
// Small trusted output — execFile
const { stdout } = await execFileAsync("git", ["rev-parse", "HEAD"]);
console.log(stdout.trim());