In Node.js, the process of executing command line binaries is handled through the child_process module. Whether you need to execute a command or handle process I/O with streams, there are options to meet your requirements.
To execute a command and fetch its complete output as a buffer, use child_process.exec():
const { exec } = require('child_process'); exec('command', (error, stdout, stderr) => { // command output is in stdout });
If you need to handle process I/O with streams, use child_process.spawn():
const { spawn } = require('child_process'); const child = spawn('command', ['args']); child.stdout.on('data', (chunk) => { // output will be here in chunks });
Node.js also supports synchronous spawn and exec methods. These methods do not return an instance of ChildProcess:
const { execSync } = require('child_process'); let stdout = execSync('command');
In case you need to execute a file rather than a command, use child_process.execFile():
const { execFile } = require('child_process'); execFile('file', ['args'], (error, stdout, stderr) => { // command output is in stdout });
The above is the detailed content of How Can I Execute Command Line Binaries and Files in Node.js?. For more information, please follow other related articles on the PHP Chinese website!