Calling a node.js script from inside java

前端 未结 4 2088
感情败类
感情败类 2020-12-08 08:00

How can I call a node.js inside java and save the console.log values in a String variable?

相关标签:
4条回答
  • 2020-12-08 08:32

    Cant be done. For normal JS you can use Rhino, but for Node you will need to make sure it is in the PATH then call Runtine.exec or a ProcessBuilder with ByteArrayOutputsreams that can later be cinverted to strings. The node code cannot access Java and vice versa.

    0 讨论(0)
  • 2020-12-08 08:34

    Check these projects which allow you to run node.js scripts inside the jvm

    • https://github.com/apigee/trireme (Apigee)
    • http://nodyn.io/ (Redhat)
    • https://avatar-js.java.net/ (Oracle)
    0 讨论(0)
  • 2020-12-08 08:44

    Yes, It is very eassy to execute and node.js file using java.

    import java.io.FileReader;
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    
    public class RunScriptFileDemo {
      public static void main(String[] args) {
          ScriptEngineManager manager = new ScriptEngineManager();
          ScriptEngine engine = manager.getEngineByName("js");
          try {
             FileReader reader = new FileReader("yourFile.js");
             engine.eval(reader);
             reader.close();
          } catch (Exception e) {
             e.printStackTrace();
          }
       }
    }
    
    0 讨论(0)
  • 2020-12-08 08:46

    It is possible for a Java application to communicate with a running Node.JS application. For instance, you can have a Node.JS app running on an available port and the Java app can communicate with it via tcp sockets.

    http://nodejs.org/api/net.html

    Or you can create an http server and expose a rest service which your Java app can consume.

    http://nodejs.org/api/http.html

    Or as md_5 says, you can use Runtime.exec and then call getInputStream on the resulting process.

    http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

    The ways you can communicate between node.js and Java are no different from other cross application communication that can be done.

    It is also possible to invoke Java code from your Node.JS application using something like node-java.

    https://github.com/nearinfinity/node-java

    0 讨论(0)
提交回复
热议问题