How to run javascript code without using a browser _ javascript tips-js tutorial

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