Advanced Node.js Interview QuestionsAdvancedConcept
Node.js · Question 70
What is the child_process module in Node.js?
Direct answer
child_process spawns separate OS processes — run shell commands, CLI tools, or other Node scripts; communicate via stdin/stdout/stderr pipes or IPC; used by AceDevHub compiler runner to execute user code in isolated processes.
Unlike worker_threads (threads), child_process creates full OS processes — stronger isolation for untrusted code, native binaries, and language runtimes (python, javac).
| Method | Use case |
|---|---|
| spawn | Stream I/O, long-running processes, large output |
| exec | Buffer entire stdout/stderr, shell one-liners |
| execFile | Direct executable, no shell, safer args |
| fork | Node script with IPC channel (cluster uses this) |
- stdio pipes — 'pipe', 'inherit', or custom stream for stdin/out/err.
- Exit codes — code 0 success; non-zero error; listen on 'close' event.
- Security — never pass unsanitized user input to shell; prefer execFile with arg array.
child-process.mjs
import { spawn } from "node:child_process";
const child = spawn("node", ["runner.mjs"], {
stdio: ["pipe", "pipe", "pipe"],
env: { ...process.env, NODE_ENV: "sandbox" },
});
child.stdin.write(userCode);
child.stdin.end();
child.stdout.on("data", (chunk) => process.stdout.write(chunk));
child.on("close", (code) => console.log("exit", code));