为什么我的 exec 命令失败,但如果命令在终端中传递则有效?

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 函数运行命令时,它会检查该命令的退出代码。它假定 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)
}
})()