2017-10-20 75 views
2

我有一個shell命令,在終端運行正常但由節點的child_process執行錯誤。節點的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 
    ... 

This是剛剛運行時顯示的默認消息jq。就好像我只是跑了jq沒有前面的管道。

+0

不涉及到管道的行爲,但你並不需要在這裏'cat' (如果這是你正在運行的真正命令)。試試'jq'..filter ..'/ tmp/file.json'。 – randomir

+0

@randomir在我的情況下,我確實需要'cat',因爲如果我運行'jq/tmp/file.json',它會打斷'unexpected'/''。當'cat'在'jq'之前解析文件時,我沒有看到這個錯誤。 (用pastebin更新問題到json) –

+1

看起來像'jq'需要強制過濾器,請嘗試:'cat file | jq'。''。這也解決了你的其他問題:'jq'。' file'。 – randomir

回答

1

如果省略了過濾器,則捕獲在jqattempts to intelligently infer the default filter中。

即,當輸出變爲終端(TTY),所述過濾器可以省略,其默認值爲.(漂亮打印)。這就是爲什麼在終端,你可以這樣寫:

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"; 
+1

'jq'。''可以簡化爲:'jq。' – peak

+1

這是真的,已更新。謝謝! – randomir