首页 > 解决方案 > 节点子进程bash脚本中的嵌套json参数

问题描述

我正在尝试使用 node 执行一个 bash 命令,该命令将嵌套的 json 对象作为参数。我发现嵌套的 json 不起作用。

例如尝试转换此 bash 命令。注意awscloudformation是一个嵌套对象。

#!/bin/bash
set -e
IFS='|'

AWSCLOUDFORMATIONCONFIG="{\
\"configLevel\":\"project\",\
\"useProfile\":true,\
\"profileName\":\"testing\"\
}"
PROVIDERS="{\
\"awscloudformation\":$AWSCLOUDFORMATIONCONFIG\
}"

amplify init \
--providers $PROVIDERS \

这是无法按预期工作的节点脚本。Providers 似乎被忽略了,并且没有像上面的 bash 脚本那样覆盖默认值。

const arguments = [
  '--providers',
  `{"awscloudformation":{"configLevel":"project","useProfile":true,"profileName":"testing"}}`,
];
const opts = { stdio: 'inherit', shell: true };
require('child_process').spawn('amplify init', getArgs(), opts);

exec更适合这里吗?看来我需要包含一个类似于$AWSCLOUDFORMATIONCONFIG在 bash 脚本中使用的变量。

有趣的是,其他未嵌套的参数似乎工作正常。例如这个放大参数工作正常:

  '--amplify',
  '{"projectName":"checking987","envName":"dev","defaultEditor":"code"}',

标签: node.jsbash

解决方案


最好在shell: false这里使用:

const arguments = [
  '--providers',
  `{"awscloudformation":{"configLevel":"project","useProfile":true,"profileName":"testing"}}`,
];
const opts = { stdio: 'inherit', shell: false };
require('child_process').spawn("amplify", ["init", ...arguments], opts);

在 shell 模式下,双引号被删除。

改编的 shell 模式版本有效:

const arguments = [
  '--providers',
  `{\\"awscloudformation\\":{\\"configLevel\\":\\"project\\",\\"useProfile\\":true,\\"profileName\\":\\"testing\\"}}`,
];
const opts = { stdio: 'inherit', shell: true };
require('child_process').spawn("amplify init", arguments, opts);

推荐阅读