GitHub Action中JavaScript脚本语法错误排查求助
解决GitHub Action脚本中的SyntaxError错误
错误定位与修正
1. 模板字符串语法错误(核心报错原因)
在findBotComment函数中,你错误地在单引号包裹的普通字符串里使用了模板字符串的${num}语法,导致JS解析时出现括号缺失的语法错误。
原错误代码:
comment.body.includes('Part # ' + ${num})
修正方案二选一:
- 直接字符串拼接:
comment.body.includes('Part # ' + num)
- 改用模板字符串:
comment.body.includes(`Part # ${num}`)
2. 变量名引用错误
在for循环的判断逻辑中,你定义的变量是botC,但判断时误用了未定义的botComment,会导致运行时错误。
原错误代码:
if (botComment) {
修正为:
if (botC) {
3. 异步操作缺少await关键字
调用GitHub REST API的方法是异步函数,必须添加await关键字,否则会产生未处理的Promise,引发后续逻辑问题。
原错误代码:
github.rest.issues.updateComment({...}) // 以及 github.rest.issues.createComment({...})
修正为:
await github.rest.issues.updateComment({...}) // 以及 await github.rest.issues.createComment({...})
完整修正后的脚本片段
const fs = require("fs"); const plan = fs.readFileSync("/tmp/plan.txt", {encoding: 'utf-8'}); const maxGitHubBodyCharacters = 65536; const { data: comments } = await github.rest.issues.listComments({ owner: context.repo.owner, repo: context.repo.repo, issue_number: context.issue.number, }) function chunkSubstr(str, size) { const numChunks = Math.ceil(str.length / size) const chunks = new Array(numChunks) for (let i = 0, o = 0; i < numChunks; ++i, o += size) { chunks[i] = str.substr(o, size) } return chunks } function findBotComment(num) { const botComment = comments.find(comment => { return comment.user.type === 'Bot' && comment.body.includes(`Part # ${num}`) }) return botComment } // Split the Terraform plan into chunks if it's too big and can't fit into the GitHub Action var plans = chunkSubstr(plan, maxGitHubBodyCharacters); for (let i = 0; i < plans.length; i++) { var botC = findBotComment(i); const output = `### Part # ${i + 1} #### Terraform Format and Style 🖌\`success\` #### Terraform Initialization ⚙️\`success\` #### Terraform Plan 📖\`success\` <details><summary>Show Plan</summary> \`\`\`\n ${plans[i]} \`\`\` </details> *Pusher: @pmmalinov01, Action: \`pull_request\`, Working Directory: \`\`, Workflow: \`Terraform Plan and Apply\`*`; if (botC) { await github.rest.issues.updateComment({ owner: context.repo.owner, repo: context.repo.repo, comment_id: botC.id, body: output }) } else { await github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: output }) } }
内容的提问来源于stack exchange,提问作者Zambozo
相关产品推荐
相关产品推荐

