我正在将一个命令行库从Ruby移植到Node.js。在我的代码中,当需要时我会执行几个第三方二进制文件。我不确定如何在Node.js中最好地完成这个任务。
下面是在Ruby中调用PrinceXML将文件转换为PDF的示例:
cmd = system("prince -v builds/pdf/book.html -o builds/pdf/book.pdf")
在Node中等价的代码是什么?
我正在将一个命令行库从Ruby移植到Node.js。在我的代码中,当需要时我会执行几个第三方二进制文件。我不确定如何在Node.js中最好地完成这个任务。
下面是在Ruby中调用PrinceXML将文件转换为PDF的示例:
cmd = system("prince -v builds/pdf/book.html -o builds/pdf/book.pdf")
在Node中等价的代码是什么?
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}`);
});
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);
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
});
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
});
spawn
和exec
。上述所有方法都是异步的,并且都有对应的同步方法。它们的文档可以在这里找到。虽然它们对于脚本编写很有用,但请注意,与异步生成子进程的方法不同,同步方法不会返回ChildProcess
的实例。child.pipe(dest)
пјҢиҖҢжҳҜиҰҒдҪҝз”Ёchild.stdout.pipe(dest)
е’Ңchild.stderr.pipe(dest)
пјҢдҫӢеҰӮchild.stdout.pipe(process.stdout)
е’Ңchild.stderr.pipe(process.stderr)
гҖӮиҜ·жіЁж„ҸдёҚиҰҒж”№еҸҳеҺҹж„ҸпјҢдҪҝзҝ»иҜ‘жҳ“жҮӮгҖӮ - ComFreekecho "hello"
和 echo "world"
。 - Cameronc:windows\system32\osk.exe
? - Mathankumar Kv15.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 v14.15.4文档 和 Node.js v12.20.1文档 同样适用。
'cmd',['/c','dir']
这个命令。至少在我之前一直苦苦搜寻为什么没有参数的'dir'
不起作用,后来才想起使用这个命令……;) - AndyO你正在寻找 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}`);
}
});
childProc.stdout.on("data", fn)
。 - hgoebl自版本4以来,最接近的替代方法是child_process.execSync
方法:
const {execSync} = require('child_process');
let output = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');
⚠️ 注意,execSync
调用会阻塞事件循环。execSync
时,是否会创建一个child_process
?并且它会在命令执行后立即被删除吗?因此不会有内存泄漏? - NiCk Newman现在您可以按以下方式使用shelljs(从node v4开始):
var shell = require('shelljs');
shell.echo('hello world');
shell.exec('node --version');
使用以下方式安装
npm install shelljs
const exec = require("child_process").exec
exec("ls", (error, stdout, stderr) => {
//do whatever here
})
如果您想要与最佳答案非常相似但也是同步的内容,那么这将起作用。
var execSync = require('child_process').execSync;
var cmd = "echo 'hello world'";
var options = {
encoding: 'utf8'
};
console.log(execSync(cmd, options));
我刚刚编写了一个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. ---------------');
});
使用这个轻量级的npm
包:system-commands
在这里查看。
像这样导入它:
const system = require('system-commands')
像这样运行命令:
system('ls').then(output => {
console.log(output)
}).catch(error => {
console.error(error)
})
如果不介意依赖并且想使用 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);