所有的编程语言都有执行系统命令的接口, Node.JS 也不例外, 比如删除调用 shell 命令, 将一个 html 文件转换成 PDF 文件, 如果是 PHP, 很简单:
- <?PHP
- `prince -v builds/pdf/book.html -o builds/pdf/book.pdf`
在 PHP 里系统命令可以放在反单引号 (`) 里执行. 如果你要是使用 Node.JS, 你需要调用引用 http://nodejs.org/api/child_process.html 模块:
- 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) {
- // 获取命令执行的输出
- });
这里使用的是 child_process.exec 来在 Node.JS 程序里执行系统命令. 如果你想在 shell 里执行命令并且要处理命令输出的 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);
如果你想在 Node.JS 里执行的是一个文件, 而不是一个简单的命令, 那你就需要使用 child_process.execFile, 这个方法的参数几乎和 spawn 一样, 只是多了第四个回调函数参数, 和 exec 里的回调函数参数一样:
- var execFile = require('child_process').execFile;
- execFile(file, args, options, function(error, stdout, stderr) {
- // command output is in stdout
- });
上面的这些方法在 Node.JS 里都是异步执行的, 到但有时候我们需要同步执行一些任务, 下面的一些代码例子是使用同步的方法调用系统命令执行任务:
- '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()}` );
- const execSync = require('child_process').execSync;
- var cmd = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');
来源: http://www.webhek.com/post/execute-a-command-line-binary-with-node-js.html