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

Amazon Linux运行打包CLI程序时yargs argv缺失命令参数问题

问题现象

使用yargs实现CLI应用参数解析时,Windows开发环境下可正常识别传入的命令与参数;将node_modules作为bundled dependencies一并打包,部署到Amazon Linux环境运行时,yargs解析得到的argv对象未包含任何传入的命令与参数。

部署时的执行命令如下:

./yargcmd.sh --command command1 --param1 2022-06-20T00:00:00.000Z --param2 2022-06-20T23:59:59.999Z

核心业务代码如下:

export class Cli {
    private commandMap: { [key: string]: any; } = {};

    constructor() {
        this.commandMap['command1'] = new Command1();
        this.commandMap['command2'] = new Command2();
        this.commandMap['command3'] = new Command3();
        this.commandMap['command4'] = new Command4();
    }

    public async execute(): Promise<string> {
        const argv = yargs.argv;
        console.log(JSON.stringify(argv));
        let command = this.commandMap[argv.command];
        if ( command != null) {
            await command.execute();
        } else {
            if ( argv.command != null ) {
                console.log('Command not found: ' + argv.command);
            }
            console.log('***** Available Commands *****');
            for(let key in this.commandMap) {
                console.log(this.commandMap[key].help());
            }
        }

        return 'Executed command: ' + argv.command;
    }
}

let cli: Cli = new Cli();
cli.execute();

不同环境下序列化打印的argv结果:

  • Windows环境(正常):{"_":[],"command":"command1","param1":"2022-06-20T00:00:00.000Z","param2":"2022-06-20T23:59:59.999Z","$0":"Cli.js"},所有命令与参数可正常识别
  • Amazon Linux环境(异常):{"_":[],"$0":"Cli.js"},所有命令与参数字段完全丢失
排查与修复方案
  • 优先检查启动脚本yargcmd.sh的参数透传配置
    该问题90%以上的诱因是shell脚本未将入参传递给内部的node进程。如果脚本内容为如下形式:

    #!/bin/bash
    node /your/project/path/Cli.js
    

    执行脚本时附带的所有参数只会被shell脚本本身接收,不会传递给node进程,yargs读取进程参数时自然无法获取到自定义命令和参数。
    修复方式为在启动node的命令末尾添加"$@",将脚本接收到的所有参数原样透传给node进程:

    #!/bin/bash
    node /your/project/path/Cli.js "$@"
    

    注意:必须用双引号包裹$@,避免包含空格的参数被错误拆分。

  • 若脚本已正确配置参数透传,依次排查以下两点:

    1. 修正yargs解析逻辑:避免隐式读取yargs.argv,部分打包工具会在构建阶段提前执行模块初始化逻辑,导致yargs在进程参数未就绪时就完成解析。建议显式传入参数列表调用parse方法,规避时序问题:
      // 替换原有 const argv = yargs.argv 写法
      const argv = yargs(process.argv.slice(2)).parse();
      
    2. 修复脚本格式问题:如果shell脚本是在Windows环境下编辑的,文件默认使用CRLF换行符,上传到Linux后会导致shebang行解析异常,也可能引发参数传递故障。可执行dos2unix yargcmd.sh转换换行符,重新赋予执行权限后再测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 11:31:08