1

I have been using node.js for development. There is a situation in which I need to execute program written in Java. A simple class having a main function.By the way I have .java file with me. So what I need is to call a java program from Node.js app so that the program starts and do some calculations and then print it on screen. I need that processed value in some node.js variable so that I could use it in my node.js express app.

I've already seen some solutions suggesting child process, spawn and exec etc. But I have tried all of them and getting error. Some time ENONET error some time buffer error. May be it is due to the fact that answers are given for windows platform while I'm using Ubuntu OS. My Main.java file is residing on parent directory of node.js program. Need your valuable support.

3
  • Could you provide what exactly you do? And another question - you tried to run *.java file or *.class? Commented Nov 19, 2019 at 6:18
  • using .java file. Had reference from stackoverflow.com/questions/18815734/… Commented Nov 19, 2019 at 6:32
  • 1
    I think you need to compile Java in .class first, or even better generate jar. Then apply the solution from your message Commented Nov 19, 2019 at 9:23

1 Answer 1

1

Different answers are available at forum however, I'm providing breakup of steps involved to run a java programs. Step 1. Creation of .jar file from yourCode.java. (Need to install Java development kit at your system). The process is explained in the link https://www.tecmint.com/create-and-execute-jar-file-in-linux/

Once done place your .jar file in the parent directory of node.js app and use following code. It is a complete function which can be called from express app.

        const executeJava = () => {
        return new Promise((resolve, reject) => {
            const child = exec('java -jar main.jar', function (error, stdout, stderr) {
                console.log('Value at stdout is: ' + stdout); // here you get your result. In my case I did'nt needed to pass arguments to java program.
                resolve(stdout);
                if (error !== null) {
                    console.log('exec error: ' + error);
                    reject(error);
                }
            });
        })
    }

// you can call this function from your node.js express app using
// const myResult = await executeJava();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.