3

Is it possible to run a Java file from a node application, and get the response of it? For example something as simple as:

package com.app;

public class App {
    public static void main(String[] args) {
        System.out.println('Hello World');
    }
}

And I want to get the response Hello World

Kousha
  • 32,871
  • 51
  • 172
  • 296
  • 1
    Your node app would have to compile that class, then sure, you can capture the standard output just like any other process... – OneCricketeer Oct 25 '16 at 20:25
  • 1
    I am curious to see your use case here, if you don't mind – so-random-dude Oct 25 '16 at 20:37
  • There is another question and answer like this in here. http://stackoverflow.com/questions/5775088/is-it-possible-to-execute-an-external-program-from-within-node-js – Hakan SONMEZ Oct 25 '16 at 20:51
  • Run the Java file with `.spawn()` or `.exec()` like you would run any external process and then examine `stdout`. – jfriend00 Oct 25 '16 at 21:26

2 Answers2

5
  1. Compile you java file
  2. execute it by node? in this way

let childProcess = require('child_process').spawn(
      'java', ['-jar', 'yureJavaFile.jar']
    );

childProcess.stdout.on('data', function(data) {
    console.log(data);
});

childProcess.stderr.on("data", function (data) {
    console.log(data);
});
Denis Lisitskiy
  • 1,285
  • 11
  • 15
  • Hello Sir i too have same problem but in my case on running of jar it accepts multiple inputs from jar ...how to get this from node – sameer joshi Dec 04 '18 at 11:25
1

If you want to do more complex interaction between java and node you may want to look at node-java. It allows you to create and handle Java objects in a node application and call Java functions in external java class files or jars.

var ArrayList = java.import('java.util.ArrayList');
var list3 = new ArrayList();
list3.addSync('item1');
list3.equalsSync(list1); // true
Roberg
  • 1,083
  • 1
  • 12
  • 11