The scripting language in the console is JavaScript, so you can evaluate code directly from the command line.

You can also extend the console and register new commands by including script files. To include a script file, use the "inc" command, followed by the URL of the file, for example:

  inc http://example.com/script.js

In your script file you can execute any JavaScript code you want. As the code only affects you and your session, anything you run will only result in changes to you.

The CLI object is the main console API. This contains all of the internal functions that the console uses. As a simple example, we'll create a script which outputs a line of text to the console. To do this, we'll register a new command using the "reg" method.

  CLI.reg('hello', function() {
      this.line('Hello World');
  });

The "reg" method accepts 2 arguments, the "name" of the new command, and the "function" that will run when the command is called. The scope of "this" within a command is a reference to the CLI object. Here we use the "line" command to print "Hello World" to the console.

Lets modify the command to recieve an input query. To do this we simply modify the function to use the "query" method to collect the user's input.

  CLI.reg('hello', function() {
      this.line(this.query());
  });

Now, we'll add some arguments to the command. Lets add "r", which will reverse the input query, and "u", which will convert it to upper case.

  CLI.reg('hello', function() {
      var out = this.query();
      if (this.args().length > 0) {
          switch (this.arg(0).name) {
              case 'r':
                  out = this.query()
                            .split('')
                            .reverse()
                            .join('');
                  break;
              case 'u':
                  out = this.query()
                            .toUpperCase();
                  break;
          }
      }
      this.line(out);
  });

The "args" method returns an array of the arguments recieved, and the "arg" method accepts a numeric index or an argument name, returning an object containing the "name" and "value" as properties, or false if an argument was not found.

© COPYRIGHT 2005-2010 JAMES WATTS. ALL RIGHTS RESERVED.