Execute a Command Line Binary with node.js

Better Stack Team
Updated on April 4, 2024

You can execute a command line binary in Node.js using the child_process module. Here's a simple example:

 
const { exec } = require('child_process');

const binaryPath = '/path/to/your/binary'; // Replace with the actual path to your binary

exec(binaryPath, (error, stdout, stderr) => {
  if (error) {
    console.error(`Error: ${error.message}`);
    return;
  }

  if (stderr) {
    console.error(`stderr: ${stderr}`);
    return;
  }

  console.log(`stdout: ${stdout}`);
});

In this example:

  1. Replace /path/to/your/binary with the actual path to your binary executable.
  2. The exec function is used to execute the binary. It takes a command string as its first argument and a callback function as its second argument.
  3. The callback function is called when the process is complete. It receives three parameters: error, stdout, and stderr.
    • error: An object with details about the error if the command failed.
    • stdout: The standard output of the command.
    • stderr: The standard error of the command.
  4. Check for errors and handle the output accordingly.

Note: If you need to provide arguments to your binary, you can include them in the command string. For example:

 
const binaryPath = '/path/to/your/binary';
const argument1 = 'arg1';
const argument2 = 'arg2';

exec(`${binaryPath} ${argument1} ${argument2}`, (error, stdout, stderr) => {
  // ...
});

Keep in mind that using exec has some security implications, especially if you're constructing the command string with user input. In such cases, consider using spawn or execFile with an array of arguments to avoid command injection vulnerabilities.