I wrote a small program in js, but I think it is quite troublesome to use a browser to run it. The following describes how to use a java program to call a javascript program, if you have similar requirements, please refer to the following: I hope it will be helpful to everyone. Sometimes we want to write a small program using js, but it is quite troublesome to use a browser to run it, now let's take a look at how to use a java program to call javascript programs so that javascript code can be executed without using a browser.
This is because I encountered such a problem in a project I have been working on over the past few days. I have a javascript script, however, other code of this project is written in C \ C ++. It is too troublesome to convert js Code into C, so I just want to call javascript code directly under C, or there is a tool in shell that can directly run js Code without using a browser. Now you can use java code to call javascript code. You can write a shell script to encapsulate it and then run js Code directly under shell.
First, if you want to install java.
The java code is as follows:
The Code is 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? 1.1.23 ");
Engine. eval (reader );
Reader. close ();
} Catch (Exception e ){
E. printStackTrace ();
}
}
}
For example, the js Code to be run is as follows:
The Code is as follows:
Function add (a, B ){
C = a + B;
Return c;
}
Result = add (10, 5 );
Print ('result = '+ Result );
Then run the following command in shell:
Javac RunScriptFile. java
Java RunScriptFile
The result is as follows:
Result = 15