使用spawn命令结合管道符(|)运用两个命令

12
我正在将一个文档转换为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",
  "-",
  "-"
]);

在这种情况下,仅第一个命令(|之前的命令)起作用。我试图做的是否可能?谢谢。
更新 - 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

不是 sh -c-。是 sh -c - Trott
2个回答

16

从管道符开始的所有内容都不是 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']);

14

如果您不想按照上述所述使用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 中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接