Alexander Mills
Alexander Mills

Reputation: 99959

Executing Node.js file in a bash script

I was looking at this example here:

https://bbs.archlinux.org/viewtopic.php?id=168479

It says I can execute JS/Node.js this way:

#!/bin/sh
exec node --harmony <<EOF
console.log("hello")
EOF

Does that make any sense to anyone? What exactly is going on?

After some Googling looks like this pulls the data between the EOF chars into stdin.

If this is possible it will allow me to solve a particular problem - namely using whichever node executable is on the user $PATH, whilst still pass the node executable flags (in this example, it's "--harmony").

If you look at the link, you only have to go down just a bit to see the code above.

Can anyone explain what this EOF syntax is about?

One specific problem I have, is that I cannot run this code:

enter image description here

My guess is that we are passing stdin to the Node.js executable, and for some reason it's not able to resolve paths correctly -

enter image description here

even though cli.js is in the same directory as cli-inspect.sh, require function is not working. In the first line we see that __dirname is ".", normally that would not be the case.

Upvotes: 0

Views: 1060

Answers (1)

cubabit
cubabit

Reputation: 2700

As mentioned in the comment to your question, it is a heredoc. It selects all text from <<EOF to the first instance of EOF. You can use other marker names, not just EOF.

It allows you to define a block of text including newlines.

The syntax has the equivalent effect of

echo 'console.log("hello")' | exec node --harmony

in that it pipes the content of the heredoc to node. But you can include newlines which is nice.

Upvotes: 1

Related Questions