Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 1 of 1
01-31-2014, 09:54 AM #1
- Join Date
- Jun 2007
- Thanked 626 Times in 605 Posts
using JS in shell and batch files
this works on windows, mac, and linux.
I'll use the windows version since it's still the most common desktop, but they are all identical expect for the look of the console prompt (as far as using node.js is concerned) in terms of the couple usages shown below.
Once you install node, which is actually really easy these days (next,next,next...), you can use "node" at the command line.
usually this just jumps into an interactive node session, but 2 flags can stop that: -p and -e.
-p prints an evaluated program
-e evaluates a program that follows, so it must be the last flag
very very simple examples:
first, as a pipe destination, same as MORE:
C:\>echo 123*456 | node -p 56088
you can interpolate shell expansions into node code:
C:\>echo '%TIME%'.bold() | node -p <b> 2:36:30.61</b>
second, you can send it a program to the right of the command using -e:
C:\>node -p -e Math.random() 0.6126509115565568
C:\>node -p -e " '%TIME%' + Date() " 2:39:24.44Fri Jan 31 2014 02:39:24 GMT-0600 (Central Standard Time)
BONUS, windows batch file.
this little guy lets you easily execute JS code in a batch file or right in the console.
if nothing else, it's a handy way to get a calculator on the console.
once node is installed, NPM adds itself to the path (reboot may be needed)
so, by adding a simple batch file to that folder, we can create a new shell command that runs in any folder.
the file, js.bat:
@node -p -e %1
note: "^Z" means [CTRL]+[Z] in the screen shot below:
C:\Users\dan\AppData\Roaming\npm>copy con js.bat @node -p -e %1 ^Z 1 file(s) copied. C:\Users\dan\AppData\Roaming\npm>cd\ C:\>js 123*456 56088
so, the next time you need a special format date stamp, a random number, or to convert data primitives on the console, node.js is your man!
Last edited by rnd me; 01-31-2014 at 09:59 AM.Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com
Users who have thanked rnd me for this post: