Nashorn and Shell Scripting (original) (raw)
Nashorn defines several built-in functions: echo
, readLine
and readFully
functions are defined only for -scripting
mode. Other extensions like quit
, exit
, load
, loadWithNewGlobal
, Object.bindProperties
are always available.
quit()
exit()
These functions are synonymous, causing the current script process to exit to the system. You can pass an integer value as the argument that represents the exit code to be returned to the system. By default, without an argument, the exit code is set to 0, meaning that the process terminated correctly.
print()
echo()
These functions are synonymous, causing the values passed in as arguments to be converted to strings, printed to stdout
separated by spaces, and followed by a new line. The implementation involves calls to java.lang.System.out.print(string)
followed by java.lang.System.out.println()
.
jjs -scripting -- arg1 jjs> var a = "Hello" jjs> print(123, $ARG[0], a, "World") 123 arg1 Hello World jjs>
readLine()
This function reads one line of input from stdin
and sends it to stdout
, or you can assign the result to a variable. You can also pass a string to the readLine()
function to get a prompt line as in the following example:
jjs> var name = readLine("What is your name? ") What is your name? Bob jjs> print("Hello, ${name}!") Hello, Bob! jjs>
readFully()
This function reads the entire contents of a file passed in as a string argument and sends it to stdout
, or you can assign the result to a variable.
jjs> readFully("text.txt") This is the contents of the text.txt file located in the current working directory.
jjs>
load()
This function loads and evaluates a script from a path, URL, or script object.
jjs> load("/foo/bar/script.js") jjs> load("http://example.com/script.js") jjs> load({name:"script.js", script:"var x = 1 + 1; x;"})
loadWithNewGlobal()
This function is similar to the load()
function, but the script is evaluated with a new global object. This is the primary method for creating a fresh context for evaluating scripts. Additional arguments (after the script) passed to loadWithNewGlobal()
are stored in the arguments
global variable of the new context.
Object.bindProperties()
This function is used to bind the properties of the first passed-in object with properties of the second passed-in object. The function enables sharing of global properties. For example, in a Document Object Model (DOM) simulation, you can share properties between the global object and the document. In a multithreading application, you can share functions across global objects of threads.
The following example shows how you can bind the global object's properties to the properties of the obj
object:
jjs> var obj = {x:34,y:100} jjs> obj.x 34 jjs> obj.y 100 jjs> x :1 ReferenceError: "x" is not defined jjs> Object.bindProperties(this,obj) [object global] jjs> x 34 jjs> y = Math.PI 3.141592653589793 jjs> obj.y 3.141592653589793 jjs>