Ways to run JavaScript code without using a browser _javascript tips

Source: Internet
Author: User
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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.