javascriptterminal

How do you run JavaScript script through the Terminal?


For instance, if you were to run a Python script you would type python filename.py. Or, if you wanted to run a C program, make filename and then ./filename. How do you do this with .js files?


Solution

  • You would need a JavaScript engine (such as Mozilla's Rhino) in order to evaluate the script - exactly as you do for Python, though the latter ships with the standard distribution.

    If you have Rhino (or alternative) installed and on your path, then running JS can indeed be as simple as

    > rhino filename.js
    

    It's worth noting though that while JavaScript is simply a language in its own right, a lot of particular scripts assume that they'll be executing in a browser-like environment - and so try to access global variables such as location.href, and create output by appending DOM objects rather than calling print.

    If you've got hold of a script which was written for a web page, you may need to wrap or modify it somewhat to allow it to accept arguments from stdin and write to stdout. (I believe Rhino has a mode to emulate standard browser global vars which helps a lot, though I can't find the docs for this now.)