You need to enable JavaScript to run this app. 如何将NPM脚本输出的JSON作为参数传递给另一个脚本命令
优惠活动
大模型
产品
解决方案
定价
更多

如何将NPM脚本输出的JSON作为参数传递给另一个脚本命令

可行解决方案

方案1:直接使用Bash命令替换(适配你当前的Git Bash环境)

利用Git Bash支持的$()命令替换语法,直接将压缩后的JSON输出作为参数值传入,修正后的scripts配置如下:

{
  "scripts": {
    "example": "bash -c 'cat ./sample.json | tr -d \" \t\n\r\"'",
    "test:override": "codeceptjs run --steps --config ./codecept.conf.js --override \"$(cat ./sample.json | tr -d ' \t\n\r')\""
  }
}

注意:执行npm run test:override时必须在Git Bash终端下运行,cmd/PowerShell不支持该类shell语法。

方案2:使用jq处理JSON(更稳定,推荐)

tr删除空白符可能误删JSON字符串值内部的有效空格,安装jq工具后用它压缩JSON更安全,配置如下:

"test:override": "codeceptjs run --steps --config ./codecept.conf.js --override \"$(jq -c . ./sample.json)\""

jq -c会自动输出合法的压缩格式JSON,不会破坏原有结构。

方案3:Node.js中转(全环境兼容)

如果需要跨终端运行,直接写Node.js脚本处理参数调用,避免shell语法兼容问题:

  1. 新建run-test.js文件:
const childProcess = require('child_process');
const fs = require('fs');

// 读取并序列化JSON
const sampleConfig = JSON.parse(fs.readFileSync('./sample.json', 'utf8'));
const overrideParam = JSON.stringify(sampleConfig);

// 调用codeceptjs命令
const testProcess = childProcess.spawn('codeceptjs', [
  'run', '--steps', '--config', './codecept.conf.js', '--override', overrideParam
], { stdio: 'inherit' });

testProcess.on('close', code => process.exit(code));
  1. 修改npm脚本配置:
"test:override": "node run-test.js"

该方案不受终端类型限制,Win10的cmd、PowerShell也能正常运行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 20:42:00