---
title: "exec vs spawn vs execFile: running shell commands from Node.js safely"
description: "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."
url: https://www.danny.engineering/answer/nodejs/exec-vs-spawn-vs-execfile-running-shell-commands-from-nodejs-safely
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T18:57:00.000Z
tags: ["Node.js"]
---

# exec vs spawn vs execFile: running shell commands from Node.js safely

## 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.


```javascript
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';

const execFileAsync = promisify(execFile);

const { stdout } = await execFileAsync('git', ['log', '-1', '--format=%H']);
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.


```javascript
// Dangerous: a filename of "x; rm -rf ~" runs rm
exec(`wc -l ${filename}`);

// Safe: filename is a single argument, never parsed by a shell
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`.


```javascript
try {
  const { stdout } = await execFileAsync('git', ['status', '--porcelain']);
  console.log(stdout ? 'Uncommitted changes' : 'Clean');
} catch (error) {
  console.error(`git failed with code ${error.code}`, error.stderr);
}
```


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.


```javascript
import { spawn } from 'node:child_process';

const child = spawn('npm', ['run', 'build'], { stdio: 'inherit' });

child.on('error', (error) => console.error('Could not start', error));
child.on('close', (code) => {
  if (code !== 0) process.exitCode = code;
});
```


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.


```javascript
import { exec } from 'node:child_process';

exec('ls *.log | wc -l', (error, stdout) => {
  if (error) throw error;
  console.log(`${stdout.trim()} log files`);
});
```


### 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.


```javascript
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.

## Related reading

- [Node.js: Child process](https://nodejs.org/api/child_process.html)
- [Node.js: Deprecated APIs](https://nodejs.org/api/deprecations.html)
