Monday, July 23, 2007

Javascript from the Command Line

I have an interest in Javascript, as I find it a very easy language to quickly put something together. It is very flexible, and its prototyping of objects instead of using class definitions makes it very easy to quickly create, well, prototypes. It always bothers me to click on a link purporting to be about the Javascript language only to discover it is about using Javascript in a browser. Most of my Javascript usage is outside of the browser using Windows Script Host.

Charles Lowell wrote in “Learning Javascript from the Command Line” about Javascript being a language in its own right, not attached to any browser. His directions, however, were for use on a Linux host rather than Windows. I have been using a WSF file to run Javascript from the command line for several years now, and since some of the comments on Reddit [http://programming.reddit.com/info/28gum/comments] indicate that this technique is not common knowledge, I share it with you here. Put the following file named jscript.wsf in your path (I put it in C:\WINDOWS:

<?XML version="1.0" standalone="yes" ?>
<package>
 <job id="jscript">
  <object id="FSO" progid="Scripting.FileSystemObject" events="true"/>
  <script language="JScript">
   <![CDATA[

var __prompt = "> ";
var __l;
var __e;
var __f;

while (true)
{
 WScript.StdOut.Write(__prompt);
 __l = WScript.StdIn.ReadLine();
 __l = __l.replace(/^\s+/, "");
 try 
 {
  switch (__l.split(/\s+/)[0].toLowerCase())
  {
   case "?":
   case "help":
    WScript.StdOut.WriteLine('Type JScript statement to evaluate or "HELP" or "QUIT"');
    break;
   
   case "exit":
   case "quit":
    WScript.Quit();
   
   case "include":
    __f = __l.replace(/^include\s+/i, "");
    __f = FSO.OpenTextFile(__f, 1);
    __l = __f.ReadAll();
    __f.Close();
   
   default:
    WScript.StdOut.WriteLine(eval(__l));
  }
 }
 catch (__e)
 {
  WScript.StdErr.WriteLine(__e.name + " " + __e.number + " (" + __e.description + "): " + __e.message);
 }
}

   ]]>
  </script>
 </job>
</package>
Now you can run Javascript from the command line:
C:\Documents and Settings\user\Desktop>jscript
> 1
1
> function f(x){return x+1}

> f
function f(x){return x+1}
> f(2)
3

If you get an error when you first try to run it, it is likely because your default script host is WScript instead of CScript. To fix this, issue the command:

C:\Documents and Settings\user\Desktop>cscript //H:CScript
The default script host is now set to "cscript.exe".

The script does not have much help, but if you look at the code, you can pretty much see the only undocumented feature, which is the ability to load script from a file using the include command.

1 comment:

  1. Brilliant! Exactly what I was looking for; a simple Javascript command line client. THANKS!

    ReplyDelete

There was an error in this gadget