將CLI 函式庫從其他語言移植到Node.js 時,執行第三方二進位檔案是一項重要任務。要在Node.js 中實現此目的,有幾個可用的模組:
對於緩衝輸出,請使用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}`); });
如果您喜歡以流的形式接收輸出,請使用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 還提供exec 和spawn 函數的同步對應項:
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);
對於ES5 之前的Node.js版本,通常使用以下方法使用:
// 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);
以上是如何在 Node.js 中執行命令列二進位?的詳細內容。更多資訊請關注PHP中文網其他相關文章!