Tuesday, June 12, 2012

Running Core JavaScript in Eclipse

With the Eclipse JavaScript Development Tools, one can create JavaScript projects, and create and edit JavaScript files. The JavaScript editor provides JavaScript syntax highlight and formatting. In this regard, the JavaScript Development Tools are pretty much like the Java Development Tools. However, unlike in the Java Development Tools, with which one can run the Java class selected in the Java Editor, one cannot simply run the JavaScript file selected in the JavaScript Editor. This article teaches, with a little "trick", one will be able to do so - almost.

Either make a jar file with the Java class in Listing 1 in it and name the jar file javascript-runner.jar, or download javascript-runner.jar from https://github.com/ted-gao/teds-code/downloads. Place javascript-runner.jar somewhere in your local file system, for example, C:\toolkit.

Listing 1

package coder.toolkit;

import java.io.FileReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class CoreJavaScriptRunner {

     * @param args - a single program argument is expected. It should be a full path
     * to the core JavaScript to run.
    public static void main(String[] args) {        
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        try {
            FileReader reader = new FileReader(args[0]);
        } catch (Exception e) {

From Eclipse Workbench, create an External Tools Configuration following the steps below:
  1. Click the menu item Run | External Tools | External Tools Configurations ...
  2. On the pop-up External Tools Configurations dialog, right click Program, then click New, as in Figure 1.
  3. Fill in the right pane of the External Tools Configurations dialog, as in Figure 2.
  4. Click the Apply button, and then the Close button to close the External Tools Configurations dialog.
Figure 1 - Create a New External Tool Configuration

Figure 2 - The Core JavaScript Runner

(Assume that you have already installed JavaScript Development Tools in Eclipse) Now You can create a JavaScript project and a JavaScript file in it. Open the JavaScript file with the JavaScript Editor, (if wanted, edit the script,) then click the External Tool button and select Core JavaScript Runner, as in Figure 3 below. Eclipse will run the selected JavaScript. And the output will be written to the Console.

Figure 3 - Run Core JavaScript

Figure 4 - An Example

Appendix - Create JavaScript Project in Eclipse

To create a JavaScript project in Eclipse, from the Workbench, follow the steps below:
  1. Click menu item File | New | Project ...
  2. On the pop-up New Project dialog appears, select JavaScript | JavaScript Project, and click the Next button.
  3. Fill in a project name, and click the Finish button.