Home >Web Front-end >JS Tutorial >How Can I Execute Command Line Binaries in Node.js Using `child_process`?

How Can I Execute Command Line Binaries in Node.js Using `child_process`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-05 16:55:12722browse

How Can I Execute Command Line Binaries in Node.js Using `child_process`?

Executing Command Line Binaries with Node.js

Executing third-party command line binaries from Node.js is straightforward using the child_process module.

Using exec for Complete Output

To execute a command and retrieve its complete output, use child_process.exec:

const { exec } = require('child_process');
exec('prince -v builds/pdf/book.html -o builds/pdf/book.pdf', (err, stdout, stderr) => {
  if (err) return;
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

Using spawn for Stream Output

To handle process I/O with streams, use child_process.spawn:

const { spawn } = require('child_process');
const child = spawn('prince', [
  '-v', 'builds/pdf/book.html',
  '-o', 'builds/pdf/book.pdf'
]);

child.stdout.on('data', (chunk) => {
  // Output chunks are received here
});

Using execFile for Executables

To execute an executable file instead of a command, use child_process.execFile:

const { execFile } = require('child_process');
execFile(file, args, options, (err, stdout, stderr) => {
  // Output is retrieved in stdout
});

Synchronous Functions

For synchronous execution, Node.js provides synchronous counterparts to these methods:

  • child_process.execSync
  • child_process.spawnSync
  • child_process.execFileSync

They do not return ChildProcess instances like their asynchronous counterparts.

Note: For Node.js versions 0.11.12 and later, the above examples apply. For earlier versions, refer to the legacy code included in the provided answer.

The above is the detailed content of How Can I Execute Command Line Binaries in Node.js Using `child_process`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn