Search code examples
javascriptjavanode.jsnode-java

How to pass a result from my java code to nodeJs?


I am writing an algo to analyze market data in Java, to visualize my data i'd like to make use of an existing charting library from tradingview. This free charting library runs on nodeJS.

I'm having a lot of trouble understanding how to populate it with my data resulting from my algorithm.

For example my Java code returns a "List< Candlestick >" object, how do i send this to the Javascript code running on the nodeJs ?

if someone would be so kind to give some global directions in how to approach this it would be very much appreciated.


Solution

  • My assumption here is that you have java code and the result you want to display is on nodejs.

    While at this moment calling data from the API is suggested, also there is one more option we can use to solve your problem. This is a good case of polyglot programming. I have used graalvm.

    Installation via sdkman GraalVM

    sdk install java 21.1.0.r11-grl
    

    NodeJS

    gu install nodejs
    

    Both Main Projects are located here https://gitlab.com/graalvm-java-to-nodejs

    • Java Project (has method which return a list)
    • NodeJS Project(loads Java Class in NodeJS and call method on class reference to get the list)

    Add any code to java library in my case I have a class which just return list of Point as given below:

    public class GraphData {
        public List<Point> getPoints() {
            return List.of(new Point(1, 1), new Point(3, 5));
        }
    }
    

    where Point is a POJO class to hold (x, y) value.

    Clone this java project https://gitlab.com/graalvm-java-to-nodejs/graalvm-simple-java and execute ./gradlew clean build this should give you a executable jar which can be executed java -jar file.jar command.

    Now, clone https://gitlab.com/graalvm-java-to-nodejs and install dependencies npm install then execute node --jvm --vm.cp=/home/ashish/IdeaProjects/graavlvm/java-lib-gvm/build/libs/java-lib-gvm-1.0-SNAPSHOT.jar bin/www

    Relevant code which interacts with java is as below:

    var GraphDataJavaRef = Java.type('in.silentsudo.GraphData');
    var graphData = new GraphDataJavaRef();
    var data = graphData.getPoints();
    

    in.silentsudo.GraphData class is loaded from the jar file which is provided to node program with argument named --jvm --vm.cp path/to/file.jar

    Once you navigate to localhost:3000, you should see

    Express Tutorial
    Welcome to Express Tutorial
    
    Response from Java class
    [Point{x=1, y=1}, Point{x=3, y=5}]