Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 1 of 1
  1. #1
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Thanked 626 Times in 605 Posts

    using JS in shell and batch files

    i recently discovered that node.js can accept javascript at/from the command-line.

    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
    note that if you're piping into node, you don't need the -e flag, it's implied.

    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()
    if you want to interpolate in this mode, you need to use a quote around the whole program:
    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
    setup and demo (type what's in red, [ENTER] after each line):
    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:\>js 123*456

    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

  2. Users who have thanked rnd me for this post:

    Dormilich (02-01-2014)


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts