【问题标题】:Execute a command line binary with Node.js使用 Node.js 执行命令行二进制文件
【发布时间】:2014-01-05 18:21:45
【问题描述】:

我正在将 CLI 库从 Ruby 移植到 Node.js。在我的代码中,我会在必要时执行几个第三方二进制文件。我不确定如何最好地在 Node 中实现这一点。

这是 Ruby 中的一个示例,我调用 PrinceXML 将文件转换为 PDF:

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

Node 中的等价代码是什么?

【问题讨论】:

标签: javascript ruby node.js command-line-interface


【解决方案1】:

您正在寻找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}`);
        }
});

【讨论】:

  • 这是正确的。但请注意,这种调用子进程的方式对标准输出的长度有限制。
  • @hgoebl,那还有什么办法呢?
  • @Harshdeep 如果标准输出较长(例如几 MB),您可以在标准输出上收听 data 事件。查看文档,但它必须类似于childProc.stdout.on("data", fn)
【解决方案2】:

对于较新版本的 Node.js (v8.1.4),事件和调用与旧版本相似或相同,但建议使用标准的较新语言功能。例子:

对于缓冲的、非流格式的输出(你一次得到所有的),使用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}`);
});

你也可以将它与 Promises 一起使用:

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();

如果您希望以块的形式逐渐接收数据(输出为流),请使用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 stderr 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.stdout);
console.log('stderr ', child.stderr);

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

使用 Node.js 生成子进程的模块在 documentation (v5.0.0) 中有详细记录。要执行命令并获取其完整输出作为缓冲区,请使用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
});

如果您需要将句柄进程 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 几乎相同,但有第四个回调参数,如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。上面描述的所有方法都是异步的,并且有一个同步的对应物。他们的文档可以在here 找到。虽然它们对脚本很有用,但请注意,与用于异步生成子进程的方法不同,同步方法不会返回 ChildProcess 的实例。

【讨论】:

  • 谢谢。这让我发疯了。有时,指出明显的解决方案会有所帮助,这样我们新手(到节点)就可以学习并使用它。
  • 注意:require('child_process').execFile() 对于需要运行文件而不是系统范围内已知命令(如这里的王子)的人来说会很有趣。
  • 您必须使用child.stdout.pipe(dest)child.stderr.pipe(dest) 而不是child.pipe(dest)(不存在),例如child.stdout.pipe(process.stdout)child.stderr.pipe(process.stderr).
  • 如果我不想将所有内容都放到一个文件中,但我想执行多个命令怎么办?也许像echo "hello"echo "world"
  • 这是执行此操作的标准方法吗?我的意思是所有包装器是如何用 nodejs 编写的?我的意思是让我们说需要运行命令的 gearman、rabbitmq 等,但它们也有一些包装器,但我在他们的库代码中找不到任何这些代码
【解决方案3】:

我刚刚写了一个 Cli 助手来轻松处理 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. ---------------');
    });

【讨论】:

【解决方案4】:

节点 JS v15.8.0、LTS v14.15.4v12.20.1 --- 2021 年 2 月

异步方法(Unix):

'use strict';

const { spawn } = require( 'child_process' );
const 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 }` );
} );

异步方法(Windows):

'use strict';

const { spawn } = require( 'child_process' );
// NOTE: Windows Users, this command appears to be differ for a few users.
// You can think of this as using Node to execute things in your Command Prompt.
// If `cmd` works there, it should work here.
// If you have an issue, try `dir`:
// const dir = spawn( 'dir', [ '.' ] );
const dir = spawn( 'cmd', [ '/c', 'dir' ] );

dir.stdout.on( 'data', ( data ) => console.log( `stdout: ${ data }` ) );
dir.stderr.on( 'data', ( data ) => console.log( `stderr: ${ data }` ) );
dir.on( 'close', ( code ) => console.log( `child process exited with code ${code}` ) );

同步:

'use strict';

const { spawnSync } = require( 'child_process' );
const ls = spawnSync( 'ls', [ '-lh', '/usr' ] );

console.log( `stderr: ${ ls.stderr.toString() }` );
console.log( `stdout: ${ ls.stdout.toString() }` );

来自Node.js v15.8.0 Documentation

Node.js v14.15.4 DocumentationNode.js v12.20.1 Documentation 也是如此

【讨论】:

  • 感谢您提供正确和简单的版本。稍微简单一点的同步版本非常适合我需要的“做某事然后扔掉”脚本。
  • 没问题!即使在某些人看来这不是“合适的”,同时拥有两者总是很好。
  • 可能值得指出的是,为了在 Windows 中执行此示例,必须使用 'cmd', ['/c', 'dir']。至少我只是在高低搜索为什么 'dir' 没有参数在我记得这一点之前不起作用...... ;)
  • 这些都没有输出到控制台。
  • @Tyguy7 你是怎么运行它的?你对控制台对象有任何覆盖吗?
【解决方案5】:

@hexacyanide 的回答几乎是完整的。 在 Windows 上,命令 prince 可能是 prince.exeprince.cmdprince.bat 或只是 prince(我不知道 gem 是如何捆绑的,但是 npm bin 带有一个 sh 脚本和一个批处理脚本 - @ 987654326@ 和 npm.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;

【讨论】:

    【解决方案6】:

    从第 4 版开始,最接近的替代方案是 child_process.execSync method

    const {execSync} = require('child_process');
    
    let output = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');
    

    ⚠️ 请注意,execSync 调用会阻止事件循环。

    【讨论】:

    • 这在最新节点上效果很好。使用execSync 时是否正在创建child_process?它会在命令后立即被删除,对吗?所以没有内存泄漏?
    • 是的,没有内存泄漏。我猜它只初始化 libuv 子进程结构而不在节点中创建它。
    【解决方案7】:
    const exec = require("child_process").exec
    exec("ls", (error, stdout, stderr) => {
     //do whatever here
    })
    

    【讨论】:

    • 请添加有关此代码如何工作以及如何解决答案的更多说明。请记住,StackOverflow 正在为将来阅读本文的人构建答案档案。
    • Al 说的是真的,但我会说这个答案的好处是,对于需要快速回复的人来说,它比阅读最佳答案要简单得多。
    【解决方案8】:

    如果您想要与top answer 非常相似但也是同步的东西,那么这将起作用。

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

    【讨论】:

    • 正是我想要的!感谢分享!
    【解决方案9】:

    如果你不介意依赖并想使用 Promise,child-process-promise 可以:

    安装

    npm install child-process-promise --save
    

    执行用法

    var exec = require('child-process-promise').exec;
    
    exec('echo hello')
        .then(function (result) {
            var stdout = result.stdout;
            var stderr = result.stderr;
            console.log('stdout: ', stdout);
            console.log('stderr: ', stderr);
        })
        .catch(function (err) {
            console.error('ERROR: ', err);
        });
    

    生成使用

    var spawn = require('child-process-promise').spawn;
    
    var promise = spawn('echo', ['hello']);
    
    var childProcess = promise.childProcess;
    
    console.log('[spawn] childProcess.pid: ', childProcess.pid);
    childProcess.stdout.on('data', function (data) {
        console.log('[spawn] stdout: ', data.toString());
    });
    childProcess.stderr.on('data', function (data) {
        console.log('[spawn] stderr: ', data.toString());
    });
    
    promise.then(function () {
            console.log('[spawn] done!');
        })
        .catch(function (err) {
            console.error('[spawn] ERROR: ', err);
        });
    

    【讨论】:

      【解决方案10】:

      现在您可以按如下方式使用 shelljs(来自 node v4):

      var shell = require('shelljs');
      
      shell.echo('hello world');
      shell.exec('node --version');
      

      安装

      npm install shelljs
      

      https://github.com/shelljs/shelljs

      【讨论】:

      • 应该不需要安装新模块
      • 这是最好的解决方案 - 他们应该在节点中包含这个...
      【解决方案11】:

      使用这个轻量级的npm 包:system-commands

      here

      像这样导入:

      const system = require('system-commands')
      

      像这样运行命令:

      system('ls').then(output => {
          console.log(output)
      }).catch(error => {
          console.error(error)
      })
      

      【讨论】:

      • 完美!非常适合我的需求。
      猜你喜欢
      • 1970-01-01
      • 2015-10-11
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多