0

I have a nodejs script that produce some output like that (it scrape website and output url) :

process.stdout.write(url)

And I want my bash to use this url (basically it just curl the url) and do some stuff.

I try node myapp | bash mybash ==> Error: write EPIPE

I try node myapp | grep 'www' ==> I see url spawn

I probably missing something about stdin stdout For the moment, in my bash I just echo $1

AKIRK
  • 109
  • 1
  • 14
  • Possible duplicate of https://stackoverflow.com/questions/53571637/command-line-arguments-vs-input-whats-the-difference – tripleee Sep 08 '21 at 18:59
  • Perhaps see also https://stackoverflow.com/questions/1504867/pipe-standard-input-and-command-line-arguments-in-bash – tripleee Sep 08 '21 at 19:00

3 Answers3

1

Your question is rather unclear, but I guess you are looking for

node myapp |
while IFS= read -r url; do
    : something with "$url"
done

If mybash expects a single command-line argument, maybe you want mybash "$url" inside the loop; though perhaps in your case you want to instead refactor your script to do the read loop instead, or as an option.

Very often you want to avoid this and write e.g. an Awk script or something instead; but this is how you read from standard input in Bash.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Sorry for my unclear question, In fact, like in bash when we pipe thing : echo XX | grep XX | awk XX ... I want to be able to do the same with a nodejs code which output something – AKIRK Sep 08 '21 at 19:03
  • But your right, I missunderstood input and line argument – AKIRK Sep 08 '21 at 19:05
  • Ok I was completly looking for read: `read foo echo "You entered '$foo'"`catch the stdout from the nodejs script – AKIRK Sep 08 '21 at 19:27
0

I often use this and integrate it with my own tools. It might help you:

const { exec } = require('child_process');
exec('shell.sh value', (err, stdout, stderr) => {
  if (err) {
    console.error(err)
  } else {
   console.log(`stdout: ${stdout}`);
   console.log(`stderr: ${stderr}`);
  }
});

Learn more about child processes.

Pierre.Vriens
  • 2,117
  • 75
  • 29
  • 42
cookie s
  • 65
  • 1
  • 6
0

The solution that fit for me was :

In nodejs file : process.stdout.write(url+' ')

And in bash file:

read url_from_node

url_list=$( echo $url_from_node | tr ' ' '\n') then process this list...

Then node myApp | mybash works

AKIRK
  • 109
  • 1
  • 14
  • You should [fix your quoting](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable). You can use `echo "${url_from_node// /$'\n'}"` though a better fix is probably to make your `node` program output one URL per line in the first place (again, perhaps, optionally, if you have mysterious but possibly legitimate reasons to prefer an objectively speaking more cumbersome output format by default). – tripleee Sep 09 '21 at 04:14