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:
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}`); });
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}`); });
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);
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);
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!