node.js - Node child_process 中的奇怪管道行为?

标签 node.js linux jq child-process

我有一个在终端中运行良好的 shell 命令,但当由 Node 的 child_process 执行时它出错了。

这是在终端中使用的命令(file.json 是一个 json 文件):

cat /tmp/file.json | jq

这里是从 child_process 运行相同的命令:

var cp = require("child_process");

var command = "cat /tmp/gen_json | jq";
cp.exec(command, function(err, stdout, stderr) {
  stderr ? console.log(stderr) : console.log(stdout);
});

产生:

jq - commandline JSON processor [version 1.5-1-a5b5cbe]
Usage: jq [options] <jq filter> [file...]

    jq is a tool for processing JSON inputs, applying the
    given filter to its JSON text inputs and producing the
    ...

这是在运行 jq 时显示的默认消息。就好像我只是在没有前面的管道的情况下运行 jq

最佳答案

捕获在 jqattempts to intelligently infer the default filter 中, 如果过滤器被省略。

即,当输出到终端 (TTY) 时,过滤器可以省略,它默认为( pretty-print ).这就是为什么在终端中你可以写:

cat file | jq           # or:  jq < file

代替:

cat file | jq .         # or:  jq . file

但是,当从 node 调用时,stdinstdout 被重定向jq 需要过滤器 参数。这就是为什么您必须明确指定它:

var command = "cat /tmp/gen_json | jq .";

或者,甚至更好(避免猫科动物虐待):

var command = "jq . /tmp/gen_json";

关于node.js - Node child_process 中的奇怪管道行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46852418/

相关文章:

python - 使用 Raspberry Pi3 实现无线传感器网络

jq:如何在 Windows 上的原始输出上输出引号

json - 使用 jq 使用来自另一个文件的值替换 JSON 中的值

node.js - 为什么我的 Express API 没有响应?

node.js - Express 中间件 - 添加 promise 拒绝处理程序

node.js - Alexa 响应和响应生成器

linux - if条件在linux shell脚本中的实现

node.js - GRUNT 安装时不带 package.json

c - 为什么 gcc 提示已经存在的库找不到?

jq - 我可以在JQ中使用相对路径或通配符吗