Java Reference
In-Depth Information
When using load() to evaluate other scripts, unex‐
pected errors may occur. JavaScript supports a form of
exception handling using try-catch blocks, so you
should use it when loading code.
Here's a quick example of how to load the D3 graphics
visualization library from Nashorn:
try {
load ( "http://d3js.org/d3.v3.min.js" );
} catch ( e ) {
print ( "Something went wrong, probably that we're not a web browser" );
}
loadWithNewGlobal()
When we use load() , it evaluates the script based on the current JavaScript
context. Sometimes we want to put the script into its own, clean context. In
these cases, use loadWithNewGlobal() instead, as this starts off the script with a
fresh, global context.
n
Shebang syntax
All the features in this section help to make jjs a good alternative language that can
easily be used to write shell scripts as bash, Perl, or other scripting languages. One
final feature helps to round out this support—the availability of the “shebang” syn‐
tax for starting up scripts written in Nashorn.
If the first line of an executable script starts with #! followed
by a path to an executable, then a Unix operating system will
assume the path points at an interpreter that is able to handle
this type of script. If the script is executed, the OS will execute
the interpreter and pass it the script file to be handled.
In the case of Nashorn, it is good practice to symlink (possibly needing sudo access)
so that there is a link from /usr/bin/jjs (or /usr/local/bin/jjs ) to the actual location of
the jjs binary (usually $JAVA_HOME/bin/jjs ). The Nashorn shell scripts can then
be written like this:
# !/ usr / bin / jjs
# ... rest of script
For more advanced use cases (e.g., long-running daemons) Nashorn can even pro‐
vide compatibility with Node.js. This is achieved by the Avatar.js portion of Project
Avatar, that is discussed in “Project Avatar” on page 347 .
The tools we've seen in this section easily enable JavaScript code to be run directly
from the command line, but in many cases we will want to go the other way. That is,
we will want to call out to Nashorn and execute JavaScript code from within a Java
program. The API that enables us to do this is contained in the Java package
Search WWH ::




Custom Search