Home >Web Front-end >JS Tutorial >How Can I Execute Command Line Binaries in Node.js Using `child_process`?
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:
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!