我有一个在终端中运行良好的 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
。
最佳答案
捕获在 jq
的 attempts to intelligently infer the default filter 中, 如果过滤器被省略。
即,当输出到终端 (TTY) 时,过滤器可以省略,它默认为。
( pretty-print ).这就是为什么在终端中你可以写:
cat file | jq # or: jq < file
代替:
cat file | jq . # or: jq . file
但是,当从 node
调用时,stdin
和 stdout
被重定向,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/