我在Node.js下使用Bluebird promise库,这太棒了!但我有一个问题:
如果你看一下Node的child_process.exec和child_process.execFile的文档,你会发现这两个函数都返回了一个ChildProcess对象.
那么推荐这种功能的方法是什么?
请注意以下工作(我得到一个Promise对象):
var Promise = require('bluebird');
var execAsync = Promise.promisify(require('child_process').exec);
var execFileAsync = Promise.promisify(require('child_process').execFile);
Run Code Online (Sandbox Code Playgroud)
但是如何才能访问原始Node.js函数的原始返回值?(在这些情况下,我需要能够访问最初返回的ChildProcess对象.)
任何建议将不胜感激!
编辑:
下面是一个使用child_process.exec函数返回值的示例代码:
var exec = require('child_process').exec;
var child = exec('node ./commands/server.js');
child.stdout.on('data', function(data) {
console.log('stdout: ' + data);
});
child.stderr.on('data', function(data) {
console.log('stderr: ' + data);
});
child.on('close', function(code) {
console.log('closing code: ' + code);
});
Run Code Online (Sandbox Code Playgroud)
但是,如果我将使用exec函数的promisified版本(上面的execAsync),那么返回值将是一个promise,而不是ChildProcess对象.这是我正在谈论的真正问题.
由于某种原因,我不明白为什么我的命令出现问题exec,我相信我遵循了我正确引用的文档和示例。当我在终端中运行此命令时,我没有遇到问题:
gitleaks --repo=https://github.com/user/repo -v --username=foo --password=bar
Run Code Online (Sandbox Code Playgroud)
但是当我尝试将其编码为模块以便我可以在 package.json 中调用它时:
const { exec } = require("child_process")
const test = `gitleaks --repo=https://github.com/user/repo -v --username=foo --password=bar`
const execRun = (cmd) => {
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout, stderr) => {
if (error) reject(error)
resolve(stdout ? stdout : stderr)
})
})
}
(async () => {
try {
const testing = await execRun(test)
console.log(testing)
} catch (e) {
console.log(e)
}
})()
Run Code Online (Sandbox Code Playgroud)
但我仍然收到错误:
{ Error: Command failed: gitleaks --repo=https://github.com/user/repo …Run Code Online (Sandbox Code Playgroud)