简体   繁体   English

在bash脚本中执行Node.js文件

[英]Executing Node.js file in a bash script

I was looking at this example here: 我在这里看这个例子:

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

It says I can execute JS/Node.js this way: 它说我可以这样执行JS / Node.js:

#!/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. 经过一些谷歌搜索看起来像这样将EOF字符之间的数据拉入标准输入。

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"). 如果可能的话,它将允许我解决一个特定的问题-即使用用户$ PATH上的任何节点可执行文件,同时仍然传递节点可执行文件标志(在此示例中为“ --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? 谁能解释这个EOF语法是什么意思?

One specific problem I have, is that I cannot run this code: 我有一个特定的问题,就是我无法运行此代码:

在此处输入图片说明

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 - 我的猜测是我们正在将stdin传递给Node.js可执行文件,由于某种原因,它无法正确解析路径-

在此处输入图片说明

even though cli.js is in the same directory as cli-inspect.sh, require function is not working. 即使cli.js与cli-inspect.sh位于同一目录中,require函数也不起作用。 In the first line we see that __dirname is ".", normally that would not be the case. 在第一行中,我们看到__dirname是“。”,通常情况并非如此。

As mentioned in the comment to your question, it is a heredoc . 如对您的问题的评论中所述,这是一个heredoc It selects all text from <<EOF to the first instance of EOF . 它从所有文字<<EOF到的第一个实例EOF You can use other marker names, not just EOF . 您可以使用其他标记名称,而不仅仅是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. 它通过管道将heredoc的内容传送到节点。 But you can include newlines which is nice. 但是您可以添加换行符,这很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM