簡體   English   中英

為什么我的 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 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM