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.
-
imho this belongs to stackoverflow.comakira– akira2011-01-25 07:21:44 +00:00Commented Jan 25, 2011 at 7:21
-
1@akira I posted it here because it concernes tool use rather than programming topics. My questions are about how an operating system handles script files, not about how to program said scripts.Just Jake– Just Jake2011-01-25 17:38:14 +00:00Commented Jan 25, 2011 at 17:38
-
It's actually quite easy to do this in Geany: stackoverflow.com/questions/12464679/…Anderson Green– Anderson Green2012-09-17 19:42:17 +00:00Commented Sep 17, 2012 at 19:42
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
12 Comments
#!/usr/bin/env node. PS: Having Node installed as root is... as bad idea, always install it in ~/.local, one should also install npm there. Otherwise one has to sudo npm for installing stuff, and you node packages can have post-install scripts ;)cd to the directory of the script that you want to run, then type ./YourScriptName to run it.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.