JavaScript Shell

The JavaScript shell provides a simple way to run scripts in batch mode or an interactive environment for exploratory programming.

Invoking the Shell

java org.mozilla.javascript.tools.shell.Main [options] file.js [script-arguments]

where options are:

-e script-source

Executes script-source as a JavaScript script.
-f script-filename
Reads filename specified by script-filename and executes it as a JavaScript script.
-opt optLevel
-O optLevel -version versionNumber

Predefined Properties

Scripts executing in the shell have access to some additional properties of the top-level object.
 

arguments

The arguments object is an array containing the strings of all the arguments given at the command line when the shell was invoked.

help()

Executing the help function will print usage and help messages.

defineClass(className)

Define an extension using the Java class named with the string argument className. Uses ScriptableObject.defineClass() to define the extension.

load([filename, ...])

Load JavaScript source files named by string arguments. If multiple arguments are given, each file is read in and executed in turn.

loadClass(className)

Load and execute the class named by the string argument className. The class must be a class that implements the Script interface, as will any script compiled by jsc.

print([expr ...])

Evaluate and print expressions. Evaluates each expression, converts the result to a string, and prints it.

quit()

Quit shell. The shell will also quit in interactive mode if an end-of-file character is typed at the prompt.

version([number])

Get or set JavaScript version number. If no argument is supplied, the current version number is returned. If an argument is supplied, it is expected to be one of 100, 110, 120, 130, or 140 to indicate JavaScript version 1.0, 1.1, 1.2, 1.3, or 1.4 respectively.

Example

Here the shell is invoked three times from the command line. (The system command prompt is shown as $.) The first invocation executes a script specified on the command line itself. The next invocation has no arguments, so the shell goes into interactive mode, reading and evaluating each line as it is typed in. Finally, the last invocation executes a script from a file and accesses arguments to the script itself.

$ java org.mozilla.javascript.tools.shell.Main -e print('hi')

hi

$ java org.mozilla.javascript.tools.shell.Main

js> print('hi')
hi
js> 6*7
42
js> function f() {
        return a;
}
js> var a = 34;
js> f()
34
js> quit()

$ cat echo.js
for (i in arguments) {
        print(arguments[i])
}
$ java org.mozilla.javascript.tools.shell.Main echo.js foo bar

foo
bar

$



back to top