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

Dav*_*son 581 javascript ruby command-line-interface node.js

我正在将一个CLI库从Ruby移植到Node.js.在我的代码中,我在必要时执行几个第三方二进制文件.我不确定在Node中如何最好地完成此任务.

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

cmd = system("prince -v builds/pdf/book.html -o builds/pdf/book.pdf")
Run Code Online (Sandbox Code Playgroud)

Node中的等效代码是什么?

hex*_*ide 990

对于更新版本的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}`);
});
Run Code Online (Sandbox Code Playgroud)

您也可以将它与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();
Run Code Online (Sandbox Code Playgroud)

如果您希望以块的形式逐渐接收数据(以流形式输出),请使用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}`);
});
Run Code Online (Sandbox Code Playgroud)

这两个功能都具有同步功能.一个例子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');
Run Code Online (Sandbox Code Playgroud)

以及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);
Run Code Online (Sandbox Code Playgroud)

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

使用Node.js生成子进程的模块在文档(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
});
Run Code Online (Sandbox Code Playgroud)

如果需要对流使用句柄处理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);
Run Code Online (Sandbox Code Playgroud)

如果您正在执行文件而不是命令,您可能希望使用child_process.execFile哪些参数几乎相同spawn,但具有第四个回调参数,例如exec检索输出缓冲区.这可能看起来像这样:

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

v0.11.12开始,Node现在支持同步spawnexec.上述所有方法都是异步的,并且具有同步对应物.可在此处找到有关它们的文档.虽然它们对脚本很有用,但请注意,与用于异步生成子进程的方法不同,同步方法不返回实例ChildProcess.

  • 谢谢.这让我疯了.有时只需指出明显的解决方案就可以了,所以我们的noobs(to node)可以学习并运行它. (16认同)
  • 注意:require('child_process').execFile()对于需要运行文件的人而不是像这里的prince这样的系统级已知命令很有用. (10认同)
  • 而不是`child.pipe(dest)`(不存在),你必须使用`child.stdout.pipe(dest)`和`child.stderr.pipe(dest)`,例如`child.stdout. pipe(process.stdout)`和`child.stderr.pipe(process.stderr)`. (2认同)

iSk*_*ore 241

节点JS v12.9.1,LTS v10.16.3v8.16.1 --- 2018年12月

异步和正确的方法(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}` );
} );
Run Code Online (Sandbox Code Playgroud)


异步方法(Windows):

'use strict';

const { spawn } = require( 'child_process' );
const dir = spawn( '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}` ) );
Run Code Online (Sandbox Code Playgroud)


同步:

'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()}` );
Run Code Online (Sandbox Code Playgroud)

来自Node.js v11.5.0文档

这同样适用于Node.js的v10.14.2文档Node.js的v8.14.1文档

  • 感谢您提供正确和简单的版本.稍微简单的同步版本对于我需要的"做某事并扔掉"脚本完全没问题. (8认同)
  • 可能值得指出的是,为了在Windows中执行此示例,必须使用`'cmd',['/ c','dir']`.至少我只是在寻找高低,为什么没有参数的''dir'在我记得之前不起作用......;) (6认同)

And*_*nak 70

您正在寻找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}`);
        }
});
Run Code Online (Sandbox Code Playgroud)

  • 如果输出标准输出较长(例如,几个MB),则@Harshdeep可以在标准输出上监听`data`事件。在文档中查找,但必须类似于`childProc.stdout.on(“ data”,fn)`。 (2认同)

Ben*_*ler 30

const exec = require("child_process").exec
exec("ls", (error, stdout, stderr) => {
 //do whatever here
})
Run Code Online (Sandbox Code Playgroud)

  • 请添加有关此代码如何工作以及如何解决答案的更多说明.请记住,StackOverflow正在为将来阅读此内容的人构建答案存档. (14认同)
  • 艾尔说的是正确的,但我会说,这个答案的好处是,与需要快速响应的人通读最重要的答案相比,它要简单得多。 (3认同)

Pau*_*kin 24

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

const {execSync} = require('child_process');

let output = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');
Run Code Online (Sandbox Code Playgroud)

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

  • 是的,没有内存泄漏。我猜它只初始化 libuv 子进程结构,而根本没有在节点中创建它。 (2认同)

Cam*_*ron 20

如果你想要一些与最佳答案非常相似但又同步的东西,那么这将是有效的.

var execSync = require('child_process').execSync;
var cmd = "echo 'hello world'";

var options = {
  encoding: 'utf8'
};

console.log(execSync(cmd, options));
Run Code Online (Sandbox Code Playgroud)


Fac*_*alm 18

现在您可以使用 shelljs(来自节点 v4),如下所示:

var shell = require('shelljs');

shell.echo('hello world');
shell.exec('node --version');
Run Code Online (Sandbox Code Playgroud)

安装

npm install shelljs
Run Code Online (Sandbox Code Playgroud)

https://github.com/shelljs/shelljs

  • 不需要安装新模块 (2认同)

Vad*_*est 14

我刚刚写了一个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;
});
Run Code Online (Sandbox Code Playgroud)

打字稿原始源文件:

 /**
 * 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. ---------------');
    });
Run Code Online (Sandbox Code Playgroud)


Ken*_*ler 10

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

看看这里

像这样导入:

const system = require('system-commands')
Run Code Online (Sandbox Code Playgroud)

运行这样的命令:

system('ls').then(output => {
    console.log(output)
}).catch(error => {
    console.error(error)
})
Run Code Online (Sandbox Code Playgroud)


Wor*_*red 6

如果你不介意依赖并想要使用promises,那么child-process-promise:

安装

npm install child-process-promise --save
Run Code Online (Sandbox Code Playgroud)

exec用法

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);
    });
Run Code Online (Sandbox Code Playgroud)

产卵用法

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);
    });
Run Code Online (Sandbox Code Playgroud)