javascript / intermediate
Snippet
Safe Process Execution using ExecFile Arguments
Using `execFile` from `node:child_process` prevents shell injection vulnerabilities. Unlike `exec`, which runs commands inside a shell interpreter, `execFile` passes arguments directly to the executable as array elements without shell expansion.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { execFile } from 'node:child_process';const userInputFilename = 'report.txt; rm -rf /';execFile('ls', ['-la', userInputFilename], (error, stdout, stderr) => {if (error) {console.error(`Execution error: ${error.message}`);return;}console.log(`Directory listing:\n${stdout}`);});
nodejs
Breakdown
1
import { execFile } from 'node:child_process';
Imports the function designed to execute binaries directly without invoking a shell.
2
execFile('ls', ['-la', userInputFilename], (error, stdout, stderr) => {
Passes potentially unsafe input safely within an array, neutralising command injection vectors.