使用带有spawn的两个命令(使用pipe |)

时间:2016-07-08 18:29:23

标签: node.js child-process spawn pdftotext unoconv

我将文档转换为内存中的pdf(unoconv)并在终端中打印(pdftotext):

unoconv -f pdf --stdout sample.doc | pdftotext -layout -enc UTF-8 - out.txt

正在工作。现在我想使用此命令与child_process.spawn

let filePath = "...",
process = child_process.spawn("unoconv", [
  "-f",
  "pdf",
  "--stdout",
  filePath,
  "|",
  "pdftotext",
  "-layout",
  "-enc",
  "UTF-8",
  "-",
  "-"
]);

在这种情况下,只有第一个命令(在|之前)有效。我可以做我想做的事吗?

感谢。

UPDATE -

结果:sh -c- ....

bash-3.2$ sh -c- unoconv -f pdf --stdout /Users/fatimaalves/DEV/xx/_input/sample.doc | pdftotext -layout -enc UTF-8 - -
sh: --: invalid option
Usage:  sh [GNU long option] [option] ...
    sh [GNU long option] [option] script-file ...
GNU long options:
    --debug
    --debugger
    --dump-po-strings
    --dump-strings
    --help
    --init-file
    --login
    --noediting
    --noprofile
    --norc
    --posix
    --protected
    --rcfile
    --restricted
    --verbose
    --version
    --wordexp
Shell options:
    -irsD or -c command or -O shopt_option      (invocation only)
    -abefhkmnptuvxBCHP or -o option
Syntax Warning: May not be a PDF file (continuing anyway)
Syntax Error: Couldn't find trailer dictionary
Syntax Error: Couldn't find trailer dictionary
Syntax Error: Couldn't read xref table

2 个答案:

答案 0 :(得分:5)

以管道开头的所有内容都不是unoconv的参数。它由shell处理,而不是由unoconv处理。因此,您无法将其作为unoconv中的参数数组的一部分传递。

根据您的需要,有很多方法可以解决这个问题。如果您知道将仅在类UNIX操作系统上运行,则可以将命令作为参数传递给sh

process = child_process.spawn('sh', ['-c', 'unoconv -f pdf --stdout sample.doc | pdftotext -layout -enc UTF-8 - out.txt']);

答案 1 :(得分:2)

如果您不想使用如上所述的sh命令,则必须创建多个child_process.spawn实例,然后像这样通过管道将它们相互连接:

const getModule = spawn('curl', [url, '-ks']);
const unTar = spawn('tar', ['-xvz', '-C', fileName, '--strip-components', 1]);
getModule.stdout.pipe(unTar.stdin);

以上代码从理论上讲将从url检索tar,然后解压缩到目录fileName

相关问题