Used to launch a new process and execute a command. It streams the input/output data of the child process (stdout and stderr) in real-time.
Returns: A object, with access to stdout and stderr as streams.
The result of the spawn function is a child process instance that implements EventEmitterAPI.
Suitable for handling large amounts of data because it streams results
Gives you fine-grained control over the child process's input/output.
Use it when you need to run a command, and you expect real-time output (e.g., streaming logs from a CLI tool).
The child_process.spawnSync() function provides equivalent functionality in a synchronous manner that blocks the event loop until the spawned process either exits or is terminated.
Handlers for events can be attached or registered to the child instance created.
The spawn method is used to create child processes for long-lived, I/O-intensive tasks. It's more efficient than exec for processes that need to stream data.
The child_process.spawn() method spawns the child process asynchronously, without blocking the Node.js event loop.
You need to offload a heavy JSON parsing task so the main event loop stays responsive. Walk me through how you'd use fork() to do that — what files you'd create, how you'd pass the data, and how you'd get the result back.
A teammate wrote a forked script that logs 'hello' but the parent never receives the message. What are the first three things you'd check in the child and parent code?
We're processing 10k user uploads per minute. Each upload needs CPU-intensive image validation. You've prototyped with fork() but memory usage grows until the pod OOMs. What's likely leaking, and how would you fix it without rewriting the validator?
A forked worker occasionally hangs and never sends its 'done' message. The parent waits forever. How would you add a timeout and cleanup so the parent can retry or mark the job failed?
Design a fork-based worker pool for a video transcoding service. You need to limit concurrency, handle backpressure when the queue backs up, and ensure zero message loss during deployments. Sketch the parent-child protocol and the scaling strategy.
Your team is migrating from fork() to worker_threads for a real-time analytics pipeline. What specific bugs or behavior changes should you watch for during the cutover, and how would you validate parity in production?
The platform team wants to deprecate fork() in favor of a unified job queue (e.g., BullMQ) across all services. You own a legacy service that forks 50+ workers for custom ML inference. Outline a migration plan that avoids downtime, preserves exactly-once semantics, and lets both systems coexist during rollout.
A security audit flags that fork() inherits the parent's open file descriptors and env vars, leaking secrets to third-party npm packages running in the child. Propose a defense-in-depth strategy that works across all existing fork usages without rewriting each child script.