Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to run Node.js scripts without invoking `node`?

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.

like image 400
Just Jake Avatar asked Jan 25 '11 05:01

Just Jake


People also ask

Can we run JavaScript without node?

You can run your JavaScript file from your terminal only if you have installed Node.

What happens if you execute the node command without any arguments?

At the very least, a script that's run without any arguments will still contain two items in the array, the node executable and the script file that is being run.

How do I run a node script locally?

The usual way to run a Node. js program is to run the globally available node command (once you install Node. js) and pass the name of the file you want to execute. While running the command, make sure you are in the same directory which contains the app.


2 Answers

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

like image 63
akira Avatar answered Sep 20 '22 15:09

akira


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.

like image 34
B T Avatar answered Sep 18 '22 15:09

B T