Is it possible to run Node.js scripts without invo

2019-01-07 13:09发布

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.

2条回答
冷血范
2楼-- · 2019-01-07 13:51

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

查看更多
来,给爷笑一个
3楼-- · 2019-01-07 14:05

You can always simply create a shell script that runs node for you.

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.

查看更多
登录 后发表回答