MyInternships.in

Core Modules

Node.js Child Processes

child_process runs external commands or other scripts from Node. spawn streams output for long-running commands, exec buffers it for short ones, and fork starts another Node process with a message channel.


What is Child Processes in Node.js?

child_process runs external commands or other scripts from Node. spawn streams output for long-running commands, exec buffers it for short ones, and fork starts another Node process with a message channel.

Child Processes example

spawn versus exec
JavaScript
import { spawn, execFile } from 'node:child_process';

// long-running, streamed output
const ff = spawn('ffmpeg', ['-i', 'in.mp4', 'out.webm']);
ff.stdout.on('data', d => console.log(String(d)));
ff.on('close', code => console.log('exited with', code));

// short command, buffered output — arguments passed safely as an array
execFile('git', ['rev-parse', 'HEAD'], (err, stdout) => {
  if (!err) console.log(stdout.trim());
});

Key points to remember

  • Prefer spawn or execFile with an argument array over exec with a command string.
  • exec runs through a shell, so unescaped user input becomes command injection.
  • exec buffers all output in memory and fails on very large results.

Common mistakes with Child Processes

  • Interpolating user input into an exec command string — a direct remote code execution hole.
  • Ignoring the exit code and treating a failed command as success.

Node.js Child Processes— Interview Questions & FAQs

What is the difference between spawn and exec in Node.js?+

spawn streams output and suits long-running commands with large output. exec buffers everything and runs through a shell, which is convenient but unsafe with untrusted input.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships