Introduction
Use execFile to run external programs or scripts safely and easily from your Node.js code without opening a shell.
Jump into concepts and practice - no test required
const { execFile } = require('child_process');
execFile(filePath, args, (error, stdout, stderr) => {
// handle results here
});execFile('node', ['--version'], (error, stdout, stderr) => { if (error) { console.error('Error:', error); return; } console.log('Node version:', stdout); });
execFile('/bin/ls', ['-l', '/'], (error, stdout, stderr) => { if (error) { console.error('Error:', error); return; } console.log('List of root directory:', stdout); });
const { execFile } = require('child_process');
// Run 'echo' command to print a message
execFile('echo', ['Hello from execFile!'], (error, stdout, stderr) => {
if (error) {
console.error('Error:', error);
return;
}
if (stderr) {
console.error('Standard error:', stderr);
return;
}
console.log('Output:', stdout.trim());
});execFile function?execFile function is designed to run executable files directly, not scripts or servers.exec, which runs commands in a shell, execFile runs the file directly, making it safer and faster.execFile from the child_process module in Node.js?const { execFile } = require('child_process');.ls is a valid executable on the system?const { execFile } = require('child_process');
execFile('ls', ['-l'], (error, stdout, stderr) => {
if (error) {
console.error('Error:', error);
return;
}
console.log('Output:', stdout);
});ls command with argument -l to list files in long format.ls exists, error is null and stdout contains the directory listing, printed as output.execFile:const { execFile } = require('child_process');
execFile('node', ['-v'], (err, stdout) => {
if (err) throw err;
console.log(stdout);
console.error(stderr);
});execFile should have three parameters: error, stdout, and stderr.stderr but does not declare it in the callback parameters, causing a ReferenceError.stderr parameter in callback -> Option C./script.sh with arguments arg1 and arg2 using execFile. Which code snippet correctly runs it and logs both output and errors safely?['arg1', 'arg2'] is correct.