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

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

Linda Hamilton
Linda HamiltonOriginal
2024-12-10 01:58:17532browse

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

Execute Command Line Binaries with Node.js

In Ruby, you can execute third-party binaries using the system method. In Node.js, there are two options for executing command line binaries: child_process.exec and child_process.spawn.

Buffered Output with child_process.exec

Use child_process.exec if you want to receive the entire output of the command at once.

const { exec } = require('child_process');
exec('cat *.js bad_file | wc -l', (err, stdout, stderr) => {
  if (err) {
    // Handle error
  } else {
    console.log(`stdout: ${stdout}`);
    console.log(`stderr: ${stderr}`);
  }
});

Streamed Output with child_process.spawn

Use child_process.spawn if you prefer to receive the output gradually in chunks as a stream.

const { spawn } = require('child_process');
const child = spawn('ls', ['-lh', '/usr']);

child.stdout.on('data', (chunk) => {
  // Data from standard output is here as buffers
});

child.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

Synchronous Execution

For synchronous execution (not recommended for large output), use the child_process.execSync and child_process.spawnSync methods.

Note: For Node.js versions before ES5, refer to the following code for handling command line execution:

Buffered Output with child_process.exec

var exec = require('child_process').exec;
var cmd = 'prince -v builds/pdf/book.html -o builds/pdf/book.pdf';

exec(cmd, function(error, stdout, stderr) {
  // command output is in stdout
});

Streamed Output with child_process.spawn

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

child.stdout.on('data', function(chunk) {
  // output will be here in chunks
});

The above is the detailed content of How Can I Execute Command Line Binaries Using Node.js?. 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