macos 是否可以在不调用 `node` 的情况下运行 Node.js 脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4806571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to run Node.js scripts without invoking `node`?
提问by Just Jake
I like javascript, so I was excited when I heard about Node.js, a V8-based Javascript runtime. I would prefer to do my shell scripting going forward in Javascript. My issue is this: how can I run my scripts without calling node ~/Scripts/myscript.js
? After I chmod +x
my script, it tries to run as a bash script instead of a Node.js javascript.
我喜欢 javascript,所以当我听说Node.js,一个基于 V8 的 Javascript 运行时,我很兴奋。我更愿意在 Javascript 中继续编写我的 shell 脚本。我的问题是:如何在不调用的情况下运行我的脚本node ~/Scripts/myscript.js
?在chmod +x
我的脚本之后,它尝试作为 bash 脚本而不是 Node.js javascript 运行。
回答by akira
Whats making your current shell starting the bash is that your current shell (bash?) has no clue about what to do with a file.js. Thats why the gods of unix invented the shebangfor:
使您当前的 shell 启动 bash 的原因是您当前的 shell(bash?)不知道如何处理 file.js。这就是为什么 unix 的众神发明了shebang的原因:
The character sequence consisting of the characters number sign and exclamation point (#!), when it occurs as the first two characters in the first line of a text file. In this case, the program loader in Unix-like operating systems parses the rest of the first line as an interpreter directive and invokes the program specified after the character sequence with any command line options specified as parameters.
由字符数字符号和感叹号 (#!) 组成的字符序列,当它作为文本文件第一行的前两个字符出现时。在这种情况下,类 Unix 操作系统中的程序加载器将第一行的其余部分解析为解释器指令,并使用指定为参数的任何命令行选项调用字符序列后指定的程序。
So, in your case I would try to put
所以,在你的情况下,我会尝试把
#!/usr/bin/env node
at the top of the script. You can see that beeing applied for example in the 'inode' (interactive node.js) shell, which might be another option to fire your scripts.
在脚本的顶部。例如,您可以在“inode”(交互式 node.js)shell 中看到 beeing 应用,这可能是触发脚本的另一种选择。
https://github.com/bancek/node-interactive-shell/blob/master/inode.js
https://github.com/bancek/node-interactive-shell/blob/master/inode.js
回答by B T
You can always simply create a shell script that runs node for you.
您始终可以简单地创建一个为您运行 node 的 shell 脚本。
Alternatively, if you want to create a script that can run in an environment that doesn't have node.js installed, you can use installer-maker.
或者,如果你想创建一个可以在没有安装 node.js 的环境中运行的脚本,你可以使用installer-maker。