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

829

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

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

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

在Node中等价的代码是什么?


3
这个库是一个很好的起点。它可以让你在所有操作系统平台上启动进程。 - mattyb
2
可能是重复的问题:在node.js中执行并获取shell命令的输出 - Damjan Pavlica
3
最简单的方法是使用child_process.exec,这里有一些优秀的例子 - drorw
12个回答

1301
对于更新版本的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中,用于生成子进程的模块在文档(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。上述所有方法都是异步的,并且都有对应的同步方法。它们的文档可以在这里找到。虽然它们对于脚本编写很有用,但请注意,与异步生成子进程的方法不同,同步方法不会返回ChildProcess的实例。

30
谢谢你,这让我感到很烦。有时候指出显而易见的解决方案对我们这些(node)新手来说是有帮助的,让我们可以学习并顺利进行下去。 - Dave Thompson
16
注意:require('child_process').execFile() 对于需要运行文件而非系统范围已知命令(例如此处的Prince)的人会很有用。 - Louis Ameline
3
дёҚиҰҒдҪҝз”ЁдёҚеӯҳеңЁзҡ„child.pipe(dest)пјҢиҖҢжҳҜиҰҒдҪҝз”Ёchild.stdout.pipe(dest)е’Ңchild.stderr.pipe(dest)пјҢдҫӢеҰӮchild.stdout.pipe(process.stdout)е’Ңchild.stderr.pipe(process.stderr)гҖӮиҜ·жіЁж„ҸдёҚиҰҒж”№еҸҳеҺҹж„ҸпјҢдҪҝзҝ»иҜ‘жҳ“жҮӮгҖӮ - ComFreek
如果我不想把所有东西都放到一个文件中,但是我想执行多个命令怎么办?比如像 echo "hello"echo "world" - Cameron
@hexacyanide,有没有可能从子进程选项中打开c:windows\system32\osk.exe - Mathankumar K
显示剩余2条评论

321

Node JS v15.8.0, LTS v14.15.4, 和 v12.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文档

Node.js v14.15.4文档Node.js v12.20.1文档 同样适用。


12
感谢您提供恰当而简洁的版本。稍微更简单的同步版本完全适合我所需的一次性“执行并丢弃”脚本。 - Brian Jorden
1
没问题!拥有两者总是很好的,即使有些人认为这并不“规范”。 - iSkore
9
可能值得指出的是,在Windows中执行这个例子需要使用'cmd',['/c','dir']这个命令。至少在我之前一直苦苦搜寻为什么没有参数的'dir'不起作用,后来才想起使用这个命令……;) - AndyO
1
这些都不会在控制台输出任何东西。 - Tyguy7
@iSkore 我正在使用('child_process').exec执行一个命令,但是它给了我一个错误错误:命令失败:unoconv -f pdf "./document.docx" 'unoconv'不被识别为内部或外部命令、可操作的程序或批处理文件。当我在git命令行工具中运行此命令时,它可以正常工作。 - Nouman Dilshad
显示剩余9条评论

86

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

这是正确的。但请注意,调用子进程的这种方式对于stdout的长度有限制。 - hgoebl
@hgoebl,那么有什么替代方案吗? - Harshdeep
2
@Harshdeep 在标准输出有大量内容(例如几MB)的情况下,您可以监听stdout上的“data”事件。请查看文档,但它应该类似于childProc.stdout.on("data", fn) - hgoebl

50

自版本4以来,最接近的替代方法是child_process.execSync方法

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

let output = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');
⚠️ 注意,execSync 调用会阻塞事件循环。

这在最新的Node上运行得很好。但是,当使用execSync时,是否会创建一个child_process?并且它会在命令执行后立即被删除吗?因此不会有内存泄漏? - NiCk Newman
2
是的,没有内存泄漏。我猜它只初始化了libuv子进程结构,而根本没有在node中创建它。 - Paul Rumkin

36

现在您可以按以下方式使用shelljs(从node v4开始):

var shell = require('shelljs');

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

使用以下方式安装

npm install shelljs

请查看https://github.com/shelljs/shelljs


10
不需要安装新模块。 - Ben Bieler
1
这对我来说确实有效,因为我遵循的所有其他答案都没有在终端输出任何内容。 - ajskateboarder

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

18
请为这段代码提供更多的解释,包括它是如何工作以及如何解决问题。请记住,StackOverflow正在建立一个面向未来读者的答案存档。 - Al Sweigart
6
阿尔所说的是真的,但我要说这个答案的好处在于它比阅读顶部答案更简单,适合需要快速回答的人。 - user6068326

34

如果您想要与最佳答案非常相似但也是同步的内容,那么这将起作用。

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

var options = {
  encoding: 'utf8'
};

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

17

我刚刚编写了一个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. ---------------');
    });

1
最新版本在此,使用示例可在CLI中使用Grunt:https://gist.github.com/Vadorequest/f72fa1c152ec55357839 - Vadorequest

13

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

这里查看。

像这样导入它:

const system = require('system-commands')

像这样运行命令:

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

完美!非常适合我的需求。 - roosevelt

11

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

安装

npm install child-process-promise --save

使用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);
    });

生成用法

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

ECMAScript模块 import...from语法

import {exec} from 'child-process-promise';
let result = await exec('echo hi');
console.log(result.stdout);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接