Search code examples
javanode.jsexpresses6-promisespawn

How to run java code in node.js express app


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.


Solution

  • 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();