More Node.js answers

by Danny
Published 2 min read

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.


_10
import { execFile } from 'node:child_process';
_10
import { promisify } from 'node:util';
_10
_10
const execFileAsync = promisify(execFile);
_10
_10
const { stdout } = await execFileAsync('git', ['log', '-1', '--format=%H']);
_10
console.log(stdout.trim());

Why it happens

#

All three live in node:child_process but work differently:

  • exec(command) starts a shell (/bin/sh on Unix, cmd.exe on 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 for stdout and stderr, 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
_10
exec(`wc -l ${filename}`);
_10
_10
// Safe: filename is a single argument, never parsed by a shell
_10
execFile('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.


_10
try {
_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.


_10
import { spawn } from 'node:child_process';
_10
_10
const child = spawn('npm', ['run', 'build'], { stdio: 'inherit' });
_10
_10
child.on('error', (error) => console.error('Could not start', error));
_10
child.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.


_10
import { exec } from 'node:child_process';
_10
_10
exec('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.


_10
execFile('git', ['log', '--', userPath]);

Common pitfalls

#
  • Building an exec string with template literals and user input. Escaping by hand is easy to get wrong; use execFile instead.
  • Passing shell: true to spawn or execFile with 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 .bat or .cmd files on Windows without a shell. Since a 2024 security fix, Node.js refuses this with EINVAL; you have to opt in with shell: true and validate the input yourself.
  • Hitting maxBuffer with exec or execFile on big output, which kills the child.
  • Using execSync or spawnSync in a server. They block the event loop until the command finishes; keep them for scripts.
#

Was this resource helpful?