使用Node.js执行命令行二进制文件

我正在将一个CLI库从Ruby移植到Node.js。 在我的代码中,我需要时执行几个第三方的二进制文件。 我不知道如何最好的在Node中做到这一点。

下面是Ruby中的一个例子,我打电话给PrinceXML将文件转换为PDF:

cmd = system("prince -v builds/pdf/book.html -o builds/pdf/book.pdf") 

什么是节点中的等效代码?

对于更新版本的Node.js(v8.1.4),事件和调用与旧版本类似或相同,但鼓励使用标准的新语言function。 例子:

对于缓冲的非stream格式化输出(您可以一次完成),请使用child_process.exec

 const { exec } = require('child_process'); exec('cat *.js bad_file | wc -l', (err, stdout, stderr) => { if (err) { // node couldn't execute the command return; } // the *entire* stdout and stderr (buffered) console.log(`stdout: ${stdout}`); console.log(`stderr: ${stderr}`); }); 

你也可以用Promise来使用它:

 const util = require('util'); const exec = util.promisify(require('child_process').exec); async function ls() { const { stdout, stderr } = await exec('ls'); console.log('stdout:', stdout); console.log('stderr:', stderr); } ls(); 

如果您希望以块的forms逐步接收数据(以stream的forms输出),请使用child_process.spawn

 const { spawn } = require('child_process'); const child = spawn('ls', ['-lh', '/usr']); // use child.stdout.setEncoding('utf8'); if you want text chunks child.stdout.on('data', (chunk) => { // data from standard output is here as buffers }); // since these are streams, you can pipe them elsewhere child.stderr.pipe(dest); child.on('close', (code) => { console.log(`child process exited with code ${code}`); }); 

这两个函数都有一个同步对象。 child_process.execSync一个例子:

 const { execSync } = require('child_process'); // stderr is sent to stdout of parent process // you can set options.stdio if you want it to go elsewhere let stdout = execSync('ls'); 

以及child_process.spawnSync

 const { spawnSync} = require('child_process'); const child = spawnSync('ls', ['-lh', '/usr']); console.log('error', child.error); console.log('stdout ', child.stderr); console.log('stderr ', child.stderr); 

注意:以下代码仍然有效,但主要针对ES5和之前的用户。

使用Node.js生成subprocess的模块在文档 (v5.0.0)中有详细logging 。 要执行命令并将其完整输出作为缓冲区获取,请使用child_process.exec

 var exec = require('child_process').exec; var cmd = 'prince -v builds/pdf/book.html -o builds/pdf/book.pdf'; exec(cmd, function(error, stdout, stderr) { // command output is in stdout }); 

如果您需要使用stream处理I / O,例如当您期望输出大量数据时,请使用child_process.spawn

 var spawn = require('child_process').spawn; var child = spawn('prince', [ '-v', 'builds/pdf/book.html', '-o', 'builds/pdf/book.pdf' ]); child.stdout.on('data', function(chunk) { // output will be here in chunks }); // or if you want to send output elsewhere child.stdout.pipe(dest); 

如果您正在执行文件而不是命令,则可能需要使用child_process.execFile ,这些参数与spawn几乎相同,但具有第四个callback参数,如exec用于检索输出缓冲区。 这可能看起来有点像这样:

 var execFile = require('child_process').execFile; execFile(file, args, options, function(error, stdout, stderr) { // command output is in stdout }); 

从v0.11.12开始 ,Node现在支持同步spawnexec 。 上面描述的所有方法都是asynchronous的,并且有一个同步对象。 他们的文档可以在这里find。 虽然它们对于脚本编写非常有用,但请注意,与用于asynchronous生成subprocess的方法不同,同步方法不会返回ChildProcess的实例。

Node JS v8.1.4 ,LTS v6.11.1v4.8.4 — 2017年7月

asynchronous和正确的方法:

 'use strict'; const spawn = require( 'child_process' ).spawn, ls = spawn( 'ls', [ '-lh', '/usr' ] ); ls.stdout.on( 'data', data => { console.log( `stdout: ${data}` ); }); ls.stderr.on( 'data', data => { console.log( `stderr: ${data}` ); }); ls.on( 'close', code => { console.log( `child process exited with code ${code}` ); }); 

同步:

 'use strict'; const spawn = require( 'child_process' ).spawnSync, ls = spawn( 'ls', [ '-lh', '/usr' ] ); console.log( `stderr: ${ls.stderr.toString()}` ); console.log( `stdout: ${ls.stdout.toString()}` ); 

从Node.js v8.1.4文档

Node.js v6.11.1文档和Node.js v4.8.4文档也是如此

您正在寻找child_process.exec

这是一个例子:

 const exec = require('child_process').exec; const child = exec('cat *.js bad_file | wc -l', (error, stdout, stderr) => { console.log(`stdout: ${stdout}`); console.log(`stderr: ${stderr}`); if (error !== null) { console.log(`exec error: ${error}`); } }); 

我只写了一个Cli helper来轻松地处理Unix / windows。

使用Javascript:

 define(["require", "exports"], function (require, exports) { /** * Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments. * Requires underscore or lodash as global through "_". */ var Cli = (function () { function Cli() {} /** * Execute a CLI command. * Manage Windows and Unix environment and try to execute the command on both env if fails. * Order: Windows -> Unix. * * @param command Command to execute. ('grunt') * @param args Args of the command. ('watch') * @param callback Success. * @param callbackErrorWindows Failure on Windows env. * @param callbackErrorUnix Failure on Unix env. */ Cli.execute = function (command, args, callback, callbackErrorWindows, callbackErrorUnix) { if (typeof args === "undefined") { args = []; } Cli.windows(command, args, callback, function () { callbackErrorWindows(); try { Cli.unix(command, args, callback, callbackErrorUnix); } catch (e) { console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------'); } }); }; /** * Execute a command on Windows environment. * * @param command Command to execute. ('grunt') * @param args Args of the command. ('watch') * @param callback Success callback. * @param callbackError Failure callback. */ Cli.windows = function (command, args, callback, callbackError) { if (typeof args === "undefined") { args = []; } try { Cli._execute(process.env.comspec, _.union(['/c', command], args)); callback(command, args, 'Windows'); } catch (e) { callbackError(command, args, 'Windows'); } }; /** * Execute a command on Unix environment. * * @param command Command to execute. ('grunt') * @param args Args of the command. ('watch') * @param callback Success callback. * @param callbackError Failure callback. */ Cli.unix = function (command, args, callback, callbackError) { if (typeof args === "undefined") { args = []; } try { Cli._execute(command, args); callback(command, args, 'Unix'); } catch (e) { callbackError(command, args, 'Unix'); } }; /** * Execute a command no matters what's the environment. * * @param command Command to execute. ('grunt') * @param args Args of the command. ('watch') * @private */ Cli._execute = function (command, args) { var spawn = require('child_process').spawn; var childProcess = spawn(command, args); childProcess.stdout.on("data", function (data) { console.log(data.toString()); }); childProcess.stderr.on("data", function (data) { console.error(data.toString()); }); }; return Cli; })(); exports.Cli = Cli; }); 

Typescript原始源文件:

  /** * Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments. * Requires underscore or lodash as global through "_". */ export class Cli { /** * Execute a CLI command. * Manage Windows and Unix environment and try to execute the command on both env if fails. * Order: Windows -> Unix. * * @param command Command to execute. ('grunt') * @param args Args of the command. ('watch') * @param callback Success. * @param callbackErrorWindows Failure on Windows env. * @param callbackErrorUnix Failure on Unix env. */ public static execute(command: string, args: string[] = [], callback ? : any, callbackErrorWindows ? : any, callbackErrorUnix ? : any) { Cli.windows(command, args, callback, function () { callbackErrorWindows(); try { Cli.unix(command, args, callback, callbackErrorUnix); } catch (e) { console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------'); } }); } /** * Execute a command on Windows environment. * * @param command Command to execute. ('grunt') * @param args Args of the command. ('watch') * @param callback Success callback. * @param callbackError Failure callback. */ public static windows(command: string, args: string[] = [], callback ? : any, callbackError ? : any) { try { Cli._execute(process.env.comspec, _.union(['/c', command], args)); callback(command, args, 'Windows'); } catch (e) { callbackError(command, args, 'Windows'); } } /** * Execute a command on Unix environment. * * @param command Command to execute. ('grunt') * @param args Args of the command. ('watch') * @param callback Success callback. * @param callbackError Failure callback. */ public static unix(command: string, args: string[] = [], callback ? : any, callbackError ? : any) { try { Cli._execute(command, args); callback(command, args, 'Unix'); } catch (e) { callbackError(command, args, 'Unix'); } } /** * Execute a command no matters what's the environment. * * @param command Command to execute. ('grunt') * @param args Args of the command. ('watch') * @private */ private static _execute(command, args) { var spawn = require('child_process').spawn; var childProcess = spawn(command, args); childProcess.stdout.on("data", function (data) { console.log(data.toString()); }); childProcess.stderr.on("data", function (data) { console.error(data.toString()); }); } } Example of use: Cli.execute(Grunt._command, args, function (command, args, env) { console.log('Grunt has been automatically executed. (' + env + ')'); }, function (command, args, env) { console.error('------------- Windows "' + command + '" command failed, trying Unix... ---------------'); }, function (command, args, env) { console.error('------------- Unix "' + command + '" command failed too. ---------------'); }); 
 const exec = require("child_process").exec exec("ls", (error, stdout, stderr) => { //do whatever here }) 

从版本4开始,最接近的select是child_process.execSync方法:

 const execSync = require('child_process').execSync; var cmd = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf'); 

请注意,此方法阻止事件循环。

如果你想要的东西非常类似于顶部的答案,但也是同步的,那么这将起作用。

 var exec = require('child_process').execSync; var cmd = "echo 'hello world'"; var options = { encoding: 'utf8' }; console.log(exec(cmd, options)); 

@ hexacyanide的答案几乎是一个完整的。 在Windows命令prince可能是prince.exeprince.cmdprince.bat或只是prince (我不知道如何gem捆绑,但npm箱带有sh脚本和批处理脚本 – npmnpm.cmd )。 如果你想编写一个在Unix和Windows上运行的可移植脚本,你必须生成正确的可执行文件。

这里是一个简单但便携的spawn函数:

 function spawn(cmd, args, opt) { var isWindows = /win/.test(process.platform); if ( isWindows ) { if ( !args ) args = []; args.unshift(cmd); args.unshift('/c'); cmd = process.env.comspec; } return child_process.spawn(cmd, args, opt); } var cmd = spawn("prince", ["-v", "builds/pdf/book.html", "-o", "builds/pdf/book.pdf"]) // Use these props to get execution results: // cmd.stdin; // cmd.stdout; // cmd.stderr; 

我有同样的问题,我发现永远。 这是一个CLI,你可以用npm来安装,而且用我的树莓派完全可以工作! 如果你想在启动时运行它,你可以安装“永久服务”。 他们将安装所有您需要的软件,随时保持您的应用程序正常运行!

看一看!

https://github.com/zapty/forever-service

https://www.npmjs.com/package/forever