![](/img/trans.png)
[英]Trying to execute command from Nodejs (exec) throw error but works in terminal
[英]Why is my exec command failing but works if the command is passed in the terminal?
出于某种原因,我不明白为什么我的exec
命令有问题,我相信我遵循了我正确引用的文档和示例。 当我在终端中运行此命令时,我没有问题:
gitleaks --repo=https://github.com/user/repo -v --username=foo --password=bar
但是当我尝试将其编码为模块时,我可以在 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)
}
})()
但我继续收到错误:
{ Error: Command failed: gitleaks --repo=https://github.com/user/repo -v --username=foo --password=bar
at ChildProcess.exithandler (child_process.js:294:12)
at ChildProcess.emit (events.js:198:13)
at maybeClose (internal/child_process.js:982:16)
at Socket.stream.socket.on (internal/child_process.js:389:11)
at Socket.emit (events.js:198:13)
at Pipe._handle.close (net.js:606:12)
killed: false,
code: 1,
signal: null,
cmd:
'gitleaks --repo=https://github.com/user/repo -v --username=foo --password=bar' }
我试图研究我的问题,看看我是否遗漏了什么并阅读:
为什么我的exec
命令失败,但我可以在终端中传递相同的命令并且它可以工作?
当exec
function 运行命令时,它会检查该命令的退出代码。 它假定 0 以外的退出代码是错误,因此在回调中传递错误。 如果gitleaks
在 repo 中发现秘密,那么它会以代码 1 退出。
这些方面的东西应该起作用:
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) {
if (error.code === 1) {
// leaks present
resolve(stdout);
} else {
// gitleaks error
reject(error);
}
} else {
// no leaks
resolve(stdout);
}
})
})
}
(async () => {
try {
const testing = await execRun(test)
console.log(testing)
} catch (e) {
console.log(e)
}
})()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.