Node.js gives you exec, execFile and spawn to run other programs. Learn how they differ, why exec can open you to command injection, and which to choose for each job.
The short answer
#Use execFile when you want the output of a command as a string, and spawn when you want to stream output or run something long-lived. Both run the program directly and take arguments as an array, so user input cannot be treated as shell syntax. Only use exec, which runs a full shell command line, for fixed commands you wrote yourself.
_10import { execFile } from 'node:child_process';_10import { promisify } from 'node:util';_10_10const execFileAsync = promisify(execFile);_10_10const { stdout } = await execFileAsync('git', ['log', '-1', '--format=%H']);_10console.log(stdout.trim());
Why it happens
#All three live in node:child_process but work differently:
exec(command)starts a shell (/bin/shon Unix,cmd.exeon Windows) and hands it one string. You get pipes, globs and variables, and the output is buffered in memory.execFile(file, args)runs the program directly with an array of arguments, no shell, and also buffers the output.spawn(file, args)runs the program directly and gives you streams forstdoutandstderr, so data arrives as it is produced.
The risk with exec is command injection. If any part of the string comes from a user, characters such as ;, && or backticks let them run their own commands.
_10// Dangerous: a filename of "x; rm -rf ~" runs rm_10exec(`wc -l ${filename}`);_10_10// Safe: filename is a single argument, never parsed by a shell_10execFile('wc', ['-l', filename]);
How to fix it
#Use execFile for short commands with output
It is the safest default for things like git, ffprobe or convert. The promisified version rejects if the command exits with a non-zero code, with the exit code on error.code and the output on error.stdout and error.stderr.
_10try {_10 const { stdout } = await execFileAsync('git', ['status', '--porcelain']);_10 console.log(stdout ? 'Uncommitted changes' : 'Clean');_10} catch (error) {_10 console.error(`git failed with code ${error.code}`, error.stderr);_10}
Buffered output is capped by maxBuffer, 1 MiB by default. Raise it, or switch to spawn, for large output.
Use spawn for streaming and long-running processes
spawn suits builds, servers and anything producing a lot of output. Set stdio: 'inherit' to pass the output straight through to your terminal.
_10import { spawn } from 'node:child_process';_10_10const child = spawn('npm', ['run', 'build'], { stdio: 'inherit' });_10_10child.on('error', (error) => console.error('Could not start', error));_10child.on('close', (code) => {_10 if (code !== 0) process.exitCode = code;_10});
Listen for error as well as close. A missing program fires error with code ENOENT rather than a non-zero exit.
Use exec only for fixed shell command lines
If you truly need shell features and every part of the string is under your control, exec is fine.
_10import { exec } from 'node:child_process';_10_10exec('ls *.log | wc -l', (error, stdout) => {_10 if (error) throw error;_10 console.log(`${stdout.trim()} log files`);_10});
Guard against option injection
Even without a shell, a user value starting with - can be read as a flag. Many tools accept -- to mark the end of options.
_10execFile('git', ['log', '--', userPath]);
Common pitfalls
#- Building an
execstring with template literals and user input. Escaping by hand is easy to get wrong; useexecFileinstead. - Passing
shell: truetospawnorexecFilewith an argument array. That puts the shell back, and recent Node.js versions print a deprecation warning (DEP0190) because the arguments are joined, not escaped. - Running
.bator.cmdfiles on Windows without a shell. Since a 2024 security fix, Node.js refuses this withEINVAL; you have to opt in withshell: trueand validate the input yourself. - Hitting
maxBufferwithexecorexecFileon big output, which kills the child. - Using
execSyncorspawnSyncin a server. They block the event loop until the command finishes; keep them for scripts.
Related reading
#Was this resource helpful?