Java Reference
In-Depth Information
jrunscript
A simple script runner for executing JavaScript as
.js
files.
jjs
A more full-featured shell—suitable for both running scripts and use as an
interactive, read-eval-print-loop (REPL) environment for exploring Nashorn
and its features.
Let's start by looking at the basic runner, which is suitable for the majority of simple
JavaScript applications.
Running from the Command Line
To run a JavaScript file called
my_script.js
with Nashorn, just use the
jrunscript
command:
n
jrunscript my_script.js
jrunscript
can also be used with different script engines than Nashorn (see
“Nas‐
horn and javax.script” on page 340
for more details on script engines) and it pro‐
vides a
-l
switch to specify them if needed:
jrunscript -l nashorn my_script.js
With this switch,
jrunscript
can even run scripts in lan‐
guages other than JavaScript, provided a suitable script engine
is available.
The basic runner is perfectly suitable for simple use cases but it has limitations and
so for serious use we need a more capable execution environment. This is provided
by
jjs
, the Nashorn shell.
Using the Nashorn Shell
The Nashorn shell command is
jjs
. This can be used either interactively, or non-
interactively, as a drop-in replacement for
jrunscript
.
The simplest JavaScript example is, of course, the classic “Hello World,” so let's look
at how we would achieve this in the interactive shell:
$
jjs
jjs
>
print
(
"Hello World!"
);
Hello
World
!
jjs
>
Nashorn interoperability with Java can be easily handled from the shell. We'll dis‐
cuss this in full detail in
“Calling Java from Nashorn” on page 342
, but to give a first
example, we can directly access Java classes and methods from JavaScript by using