Home >Web Front-end >JS Tutorial >How to run javascript code without using a browser_javascript tips

How to run javascript code without using a browser_javascript tips

WBOY
WBOYOriginal
2016-05-16 17:28:071525browse

Sometimes we want to write a small program in js, but we find it troublesome to run it using a browser. So now let's take a look at how to use a java program to call a javascript program, so that the js code can be executed without the help of a browser. .

The reason for this requirement is because I encountered such a problem in a project I was working on these days. I have a javascript script, but the other codes of this project are all written in CC. I don’t want to use js Converting the code to C felt too troublesome, so I thought it would be great if I could directly call the javascript code under C, or there would be a tool in the shell that can directly run the 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 run the js code directly under the shell.

First of all, if you want to install java.

The java code is as follows:

Copy the code 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");
engine.eval( reader);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

For example, the js code to be run is as follows:
Copy the code The code is 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 generated result is as follows:
Result = 15
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn