关于javascript:使用Node.js执行命令行二进制文件

Execute a command line binary with Node.js

我正在将一个cli库从ruby移植到node.js。在我的代码中,我在必要时执行几个第三方二进制文件。我不知道如何最好地在节点中完成这一点。

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

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

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


对于更高版本的node.js(V8.1.4),事件和调用与旧版本类似或相同,但鼓励使用标准的较新语言功能。实例:

对于缓冲的、非流格式的输出(您可以一次获得所有输出),请使用child_process.exec

1
2
3
4
5
6
7
8
9
10
11
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}`);
});

你也可以用它来承诺:

1
2
3
4
5
6
7
8
9
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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的一个例子:

1
2
3
4
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

1
2
3
4
5
6
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生成子进程的模块在文档(v5.0.0)中有很好的记录。要执行命令并获取其作为缓冲区的完整输出,请使用child_process.exec

1
2
3
4
5
6
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

1
2
3
4
5
6
7
8
9
10
11
12
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用于检索输出缓冲区)。看起来有点像这样:

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

从v0.11.12开始,节点现在支持同步spawnexec。上面描述的所有方法都是异步的,并且有一个同步的对应物。可以在这里找到它们的文档。虽然它们对于脚本编写很有用,但是请注意,与异步生成子进程的方法不同,同步方法不会返回EDOCX1的实例(11)。


节点JS v12.2.0、LTS v10.15.3v8.16.0—2019年5月

异步方法(Unix):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
'use strict';

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

< BR>

异步方法(Windows):

1
2
3
4
5
6
7
8
9
'use strict';

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

< BR>

同步:

1
2
3
4
5
6
7
8
'use strict';

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

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

来自node.js v12.2.0文档

同样适用于node.js v10.15.3文档和node.js v8.16.0文档。


您正在查找childu process.exec

示例如下:

1
2
3
4
5
6
7
8
9
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}`);
        }
});


1
2
3
4
const exec = require("child_process").exec
exec("ls", (error, stdout, stderr) => {
 //do whatever here
})


如果你想要的东西与最上面的答案非常相似,但也是同步的,那么这就可以了。

1
2
3
4
5
6
7
8
var execSync = require('child_process').execSync;
var cmd ="echo 'hello world'";

var options = {
  encoding: 'utf8'
};

console.log(execSync(cmd, options));

由于版本4,最接近的替代方案是child_process.execSync方法:

1
2
3
const execSync = require('child_process').execSync;

let cmd = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');

注意这个方法会阻塞事件循环。


我刚写了一个cli帮助程序来轻松处理unix/windows。

Javascript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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原始源文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
 /**
 * 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. ---------------');
    });


如果你不介意依赖和使用承诺,那么child-process-promise可以:

安装

1
npm install child-process-promise --save

执行使用

1
2
3
4
5
6
7
8
9
10
11
12
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);
    });

产卵利用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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);
    });

现在可以使用shelljs(从节点v4)如下:

1
2
3
4
var shell = require('shelljs');

shell.echo('hello world');
shell.exec('node --version')

@六氰化物的答案几乎是完整的。在windows命令中,prince可以是prince.exeprince.cmdprince.bat或只是prince(我不知道gems是如何捆绑的,但npm容器附带有sh脚本和批处理脚本npmnpm.cmd。如果要编写一个可移植脚本,该脚本将在UNIX和Windows上运行,则必须生成正确的可执行文件。

下面是一个简单但可移植的生成函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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;