0
0
Node.jsframework~5 mins

execFile for running executables in Node.js

Choose your learning style9 modes available
Introduction
Use execFile to run external programs or scripts safely and easily from your Node.js code without opening a shell.
You want to run a small program or script and get its output.
You need to run a system command without exposing your app to shell injection risks.
You want to run a compiled executable file directly from your Node.js app.
You want to handle the output or errors of an external program in your code.
Syntax
Node.js
const { execFile } = require('child_process');

execFile(filePath, args, (error, stdout, stderr) => {
  // handle results here
});
filePath is the path to the executable file you want to run.
args is an optional array of strings to pass as command-line arguments.
Examples
Runs the 'node' executable with the '--version' argument to print the Node.js version.
Node.js
execFile('node', ['--version'], (error, stdout, stderr) => {
  if (error) {
    console.error('Error:', error);
    return;
  }
  console.log('Node version:', stdout);
});
Runs the 'ls' command to list files in the root directory.
Node.js
execFile('/bin/ls', ['-l', '/'], (error, stdout, stderr) => {
  if (error) {
    console.error('Error:', error);
    return;
  }
  console.log('List of root directory:', stdout);
});
Sample Program
This program runs the 'echo' executable with a message argument. It prints the output from the command.
Node.js
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());
});
OutputSuccess
Important Notes
execFile does not run commands through a shell, so it is safer from shell injection attacks.
Always handle errors and standard error output to catch problems from the executable.
Use execFile when you want to run a specific executable file with arguments.
Summary
execFile runs an executable file directly without a shell.
It is safer and better for running external programs with arguments.
You get the output and errors via callback to handle in your code.