是否可以在不调用 `node` 的情况下运行 Node.js 脚本? [英] Is it possible to run Node.js scripts without invoking `node`?

查看:27
本文介绍了是否可以在不调用 `node` 的情况下运行 Node.js 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢 javascript,所以当我听说 Node.js 时我很兴奋,这是一种基于 V8 的 Javascript 运行时.我更愿意在 Javascript 中继续编写我的 shell 脚本.我的问题是:如何在不调用 node ~/Scripts/myscript.js 的情况下运行我的脚本?在我 chmod +x 我的脚本之后,它尝试作为 bash 脚本而不是 Node.js javascript 运行.

解决方案

使您当前的 shell 启动 bash 的原因是您当前的 shell (bash?) 不知道如何处理 file.js.这就是 unix 众神发明 shebang 的原因:

<块引用>由字符数字符号和感叹号 (#!) 组成的字符序列,当它作为文本文件第一行的前两个字符出现时.在这种情况下,类 Unix 操作系统中的程序加载器将第一行的其余部分解析为解释器指令,并使用指定为参数的任何命令行选项调用字符序列后指定的程序.

所以,在你的情况下,我会尝试把

 #!/usr/bin/env 节点

在脚本的顶部.例如,您可以看到在inode"(交互式 node.js)shell 中应用了 beeing,这可能是触发脚本的另一种选择.

https://github.com/bancek/node-交互式外壳/blob/master/inode.js

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.

解决方案

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 shebang for:

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.

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.

https://github.com/bancek/node-interactive-shell/blob/master/inode.js

这篇关于是否可以在不调用 `node` 的情况下运行 Node.js 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆