1

I can escape the cli arguments node consumers with -- and have hi be my arg that's used in the text node evaluates, but I can't do the same piping a value.

j at MBP in ~
$ node -e 'console.log(">", process.argv[1])' -- hi
> hi

The piping here in bash should just take stdout and add it as an arg for the command it gets piped right?

j at MBP in ~
$ echo hi | node -e 'console.log(">", process.argv[1])' --
> undefined
James T.
  • 910
  • 1
  • 11
  • 24

1 Answers1

3

The pipe | feeds the output from the echo command into stdin on the node command. You'll need to use the readline module to read in a fluid way from stdin -- there are other ways too, but this is easy enough. (stolen from here).

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
    console.log(line);
})

If you want to use the output from echo as a command line parameter, you need to use backticks:

node -e 'console.log(">", process.argv[1])' -- `echo hi`

or a subshell:

node -e 'console.log(">", process.argv[1])' -- $(echo hi)
PaulProgrammer
  • 16,175
  • 4
  • 39
  • 56
  • This is fine for small amount of text... but when I pipe in a large file (say `cat file.txt`) I get the error 'Argument list too long'. I have tried reading the line but it just hangs (I think waiting for some user input). Is there a method to pipe in large data without user prompt? – user1822391 Dec 06 '22 at 06:22
  • Yes, it's called reading a file. The typical way would be to have a command line argument like `--moreargs @somefile.txt` or using a configuration file to store common parameters `--config /some/config.json` – PaulProgrammer Dec 06 '22 at 16:22
  • I found that instead of using the argument and sub-shell, I can just pipe it from another program and have node.js read line. For example: `command1 | node -e "var fs = require('fs'); /* get fs module */ var data = fs.readFileSync(0, 'utf-8'); /* read from stdin */` – user1822391 Dec 08 '22 at 18:11