Using two commands (using pipe |) with spawn
Asked Answered
W

2

12

I'm converting a doc to a pdf (unoconv) in memory and printing (pdftotext) in the terminal with:

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

Is working. Now i want use this command with child_process.spawn:

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

In this case, only the first command (before the |) is working. Is i possible to do what i'm trying?

Thanks.

UPDATE-

Result of: 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
Wozniak answered 8/7, 2016 at 18:29 Comment(1)
It's not sh -c-. It's sh -c.Algie
C
17

If you don't want to use the sh command as explained above, you must create multiple child_process.spawn instances and then pipe them into each other like so:

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

The above code theoretically will retrieve a tar from url, and unpack into a directory fileName

Constraint answered 4/10, 2018 at 14:33 Comment(1)
This is the most cross-environment way to do this, and it doesn't introduce an extra layer of shells like the sh -c ... solutions do.Rascon
A
16

Everything starting with the pipe is not an argument to unoconv. It is processed by the shell, not by unoconv. So you can't pass it as part of the argument array in unoconv.

There are a number of ways around this, depending on your needs. If you know you will be running on UNIX-like operating systems only, you can pass your command as an argument to sh:

process = child_process.spawn('sh', ['-c', 'unoconv -f pdf --stdout sample.doc | pdftotext -layout -enc UTF-8 - out.txt']);
Algie answered 8/7, 2016 at 18:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.