Home > Net >  Regex/shell parameters expensions when using cp.spawnSync
Regex/shell parameters expensions when using cp.spawnSync

Time:12-02

I'm testing in the command line a jq command:

jq -f config/jest.jq -s reports/jest/*.json

Which outputs the content of 3 json files located under /reports/jest/, accordings to the filters I've specified under /config/jest.jq.

If I try to run the same thing within a node script like so however:

  const jq = await cp.spawnSync('jq', ['-f', configPath, '-s', folderPath]);

It fails - jq.stderr tells me he can't finds "/reports/jest/*.json". If I do this however:

  const jq = await cp.spawnSync('jq', ['-f', configPath, '-s', 'reports/jest/app.json', 'reports/jest/backend.json', ]);

Then it properly pipes both files into jq. Why is my regular expression working in the command line, but not under spawnSync? How do I need to adapt it so it reads all my json file & parse it as a single large input?

CodePudding user response:

That's not a regular expression, but a shell glob (or shell wildcard pattern). It is evaluated by your shell (sh, bash, zsh, …). spawnSync is not running a shell, but executing the binary directly, passing all arguments verbatim.

If you need a shell's behavior, you must execute a shell or resolve the wildcard somehow else. Here's a version which uses a shell:

const jq = await cp.spawnSync(
  'sh',
  [
    '-c',
    'jq -f '   configPath   ' -s ' folderPath
  ]);

Or

const jq = await cp.spawnSync(
  'sh',
  [
    '-c',
    ['jq -f', configPath, '-s', folderPath].join(' ')
  ]);
  • Related