1

Basically I need to use one library written in javascript for my java application, and I am shaking my head on how to do it. Here is the library: https://github.com/mikeemoo/jsgo. For now I am trying to get the examples working (to no avail). It says that require is not defined. As far as require('jsgo') goes, I can just shove my script into the library and I am good with it. However, I don't know how to resolve require('fs'), which is needed to read from file. This is how I launch the script:

package csgodemo;

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class DemoMain {

public static void main (String[] args) throws NoSuchMethodException, IOException, InterruptedException, ScriptException{


    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    try {
      FileReader reader = new FileReader("./script.js");
      engine.eval(reader);
      reader.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

}

}
Coderino Javarino
  • 2,819
  • 4
  • 21
  • 43
  • 1
    It's... a Node script? You'd almost certainly be better off interacting with a Node process. That said, there's https://github.com/apigee/trireme and https://avatar-js.java.net/, but... I dunno, IME it may end up being a world of hurt. – Dave Newton Nov 12 '15 at 20:59
  • To expand on what Dave says, check out this question/answer: http://stackoverflow.com/questions/5711084/java-runtime-getruntime-getting-output-from-executing-a-command-line-program - `require` is built into node (as node implements the CommonJS standard), but not into plain old Javascript. You need to run `node` (or invoke the node libraries in your `ScriptEngine`). – childofsoong Nov 12 '15 at 21:03
  • A viable option would be Rhino https://en.wikipedia.org/wiki/Rhino_(JavaScript_engine) but I didn't try it so no guarantee(but reading the wikipedia article , it looks promising). by the way it's bundled with java 6(and above I think) so maybe you have it without even knowing – niceman Nov 12 '15 at 21:22
  • Correct : Rhino got old, the new one(bundled with java 8) is Nashorn https://en.wikipedia.org/wiki/Nashorn_(JavaScript_engine) – niceman Nov 12 '15 at 21:25

0 Answers0