You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins UTF-8编码在bat脚本中失效,求解决方案

Jenkins Windows环境下Bat脚本调用Node.js中文乱码解决

问题背景

在Windows Server 2022(21H2)运行Jenkins 2.414.1时,Pipeline中通过bat脚本调用Node.js传递中文参数,出现参数截断、显示乱码的现象,Node.js输出的中文也无法正常显示。

已尝试的无效操作

  • 在jenkins.xml中添加启动参数-Dfile.encoding=utf-8
  • Jenkins系统配置中设置全局环境变量LANG=zh_CN.UTF-8、LC_ALL=zh_CN.UTF-8
  • 在bat步骤中指定encoding:'UTF-8'参数

解决方案

Windows系统命令行默认使用GBK编码(代码页936),与UTF-8不兼容,需从多层面调整编码配置:

1. 切换Windows系统区域编码为UTF-8

  • 打开「控制面板」→「区域」→「管理」→「更改系统区域设置」
  • 勾选「Beta版:使用Unicode UTF-8提供全球语言支持」
  • 重启系统生效
  • 此操作会将Windows命令行默认编码改为UTF-8,从根源解决编码不匹配问题

2. 在Bat脚本中强制切换代码页

在bat命令开头添加chcp 65001(65001为UTF-8对应的代码页),临时切换当前命令行会话的编码:

def Notify(environment, type , content ){
    echo environment
    bat script: 'chcp 65001 && node D:\\JenkinsNotify\\notify.js '+ environment+'  '+ type +' '+ content+' '+ env.WORKSPACE
}

3. 配置Node.js强制使用UTF-8编码

在Pipeline的环境变量块中添加Node.js编码参数,确保Node.js处理输入输出时使用UTF-8:

pipeline {
    agent {label 'master'}
    environment {
        LC_ALL = 'zh_CN.UTF-8'
        LANG    = 'zh_CN.UTF-8'
        NODE_OPTIONS = "--input-encoding=utf-8 --output-encoding=utf-8"
    }
    // 后续stage代码...
}

4. 完善Jenkins Java启动编码参数

修改jenkins.xml中的Java启动参数,同时设置文件编码和系统编码:

<arguments>
  -Xrs -Xmx2048m 
  -Dfile.encoding=utf-8 
  -Dsun.jnu.encoding=utf-8 
  -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle 
  -jar "%BASE%\jenkins.war" --httpPort=8080
</arguments>

修改后重启Jenkins服务生效

5. 可选:通过文件传递中文参数(避免命令行编码问题)

若直接拼接参数仍有问题,可将中文内容写入UTF-8编码的临时文件,让Node.js读取文件内容:

Pipeline代码:

def Notify(environment, type , content ){
    def paramsData = [
        environment: environment,
        type: type,
        content: content,
        workspace: env.WORKSPACE
    ]
    def paramsFile = writeFile(
        file: 'notify_params.json',
        text: new groovy.json.JsonBuilder(paramsData).toPrettyString(),
        encoding: 'UTF-8'
    )
    bat script: 'chcp 65001 && node D:\\JenkinsNotify\\notify.js '+ paramsFile
}

Node.js代码(notify.js):

const fs = require('fs');
const paramsPath = process.argv[2];
const params = JSON.parse(fs.readFileSync(paramsPath, 'utf8'));
console.log(params);
console.log('测试中文能不能正常输入');

内容的提问来源于stack exchange,提问作者zhenghao li

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 08:53:09