Sometimes we want to use JS to write a small program, but also feel that using the browser to run a lot of trouble, so now we look at how to use Java programs to invoke JavaScript programs, so you can not use the browser can execute JS code.
The reason for this demand is because these days in a project to do this problem, I have a JavaScript script, but the project's other code is written in c\c++, do not want to turn the JS code into C, feel too troublesome, So it would be nice if you could just call JavaScript code directly under C, or there would be a tool in the shell that could run the JS code without the help of a browser. You can now call JavaScript code using Java code, you can write a shell script to encapsulate it and run the JS code directly under the shell.
First, if you want to install Java.
The Java code is as follows:
Copy Code code as follows:
Import Java.io.FileReader;
Import Javax.script.ScriptEngine;
Import Javax.script.ScriptEngineManager;
public class Runscriptfile {
public static void Main (string[] args) {
Scriptenginemanager manager = new Scriptenginemanager ();
ScriptEngine engine = Manager.getenginebyname ("JS");
try {
FileReader reader = new FileReader ("Testfile.js");
Engine.eval (reader);
Reader.close ();
catch (Exception e) {
E.printstacktrace ();
}
}
}
For example, to run the JS code as follows:
Copy Code code as follows:
function Add (A, b) {
c = a + B;
return C;
}
result = Add (10, 5);
Print (' result = ' + result);
Then run in the shell:
Javac Runscriptfile.java
Java runscriptfile
The resulting results are as follows:
result = 15