将 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中文网其他相关文章!