Home > Web Front-end > JS Tutorial > How to Execute Command Line Binaries in Node.js?

How to Execute Command Line Binaries in Node.js?

Patricia Arquette
Release: 2024-12-27 06:46:09
Original
450 people have browsed it

How to Execute Command Line Binaries in Node.js?

Executing Command Line Binaries in Node.js

Executing third-party binaries is an essential task when porting CLI libraries from other languages to Node.js. To achieve this in Node.js, there are several modules available:

child_process.exec

For buffered output, use exec:

const { exec } = require('child_process');
exec('cat *.js bad_file | wc -l', (err, stdout, stderr) => {
  if (err) return; // Node couldn't execute the command

  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});
Copy after login

child_process.spawn

If you prefer to receive output as a stream, use spawn:

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

// For text chunks, use `child.stdout.setEncoding('utf8');`
child.stdout.on('data', (chunk) => { /* data in chunks */ });

// Pipe the stream elsewhere
child.stderr.pipe(dest);

child.on('close', (code) => { console.log(`Exited with code ${code}`); });
Copy after login

Synchronous Options

Node.js also provides synchronous counterparts to the exec and spawn functions:

const { execSync } = require('child_process');
let stdout = execSync('ls');

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

console.log('error', child.error);
console.log('stdout ', child.stdout);
console.log('stderr ', child.stderr);
Copy after login

Historical Support

For versions of Node.js prior to ES5, the following methods were commonly used:

// Complete output as a buffer
var exec = require('child_process').exec;
exec('prince -v builds/pdf/book.html -o builds/pdf/book.pdf',
  function(error, stdout, stderr) { // command output in stdout });

// Handling large output chunks with streams
var spawn = require('child_process').spawn;
var child = spawn('prince', ['-v', 'builds/pdf/book.html', '-o', 'builds/pdf/book.pdf']);

// Output in chunks
child.stdout.on('data', (chunk) => { /* data in chunks */ });

// Piping output
child.stdout.pipe(dest);
Copy after login

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template