Intermediate LevelNode JS
Why is child_process.execFile() safer and faster than child_process.exec() for running system binaries?
❓ Interview Prompt: execFile("git", ["status"]) invokes the executable binary directly without spawning a subshell (/bin/sh). Eliminates shell command injection vulnerabilities and reduces OS process spawning latency.
1. 'child_process.exec()' (Unsafe!):
Spawns a shell environment ('/bin/sh -c'). If user input is interpolated directly into the command string, attackers can execute arbitrary shell commands (Command Injection Attack)!
2. 'child_process.execFile()' (Secure!):
Invokes target binaries directly without spawning a shell, passing arguments as a safe array that cannot trigger shell command injections.
Code Implementation Example
javascript
import { execFile } from 'node:child_process';
const userInput = 'file.txt; rm -rf /'; // Malicious input!
// SAFE: execFile passes userInput as a string argument, NOT a shell command!
execFile('ls', ['-lh', userInput], (error, stdout) => {
if (error) console.error('Safe error handling:', error.message);
});💡Executing binary commands safely using execFile to prevent command injection.
🎯 Interview Key Takeaway
Always use child_process.execFile() instead of exec() to prevent shell command injection security vulnerabilities.
#execFile#child_process#Security#Command Injection#Intermediate
Back to all Node JS Questions→