Many of the situation we need to interact with the other programs. Here is a small demo on how to invoke or execute the jar.

In Node js, the “child_process” is the module which will do the needful. Through chlid_process, we can execute OS command.

Here have used one java program which takes input from the command line and prints the value which is in command line execution.

Java Program

Below is the java program we have used.

public class DemoCall {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(args[0]);

	}

}

We will create an executable jar (invoke-jar) from this program. We will invoke that jar from the command line.

java -jar invoke-jar "Jar is invoked by Node js"

if you want to know about how to create the executable jar, please click here.

Node.js Program

We have created “child_process” object and call exec()  function to pass command line parameters to execute the jar. When the process will run, it will invoke the jar and output will be printed on the console. We have a file called “executejar.js”.Below is the code,

const exec = require('child_process').exec;
const childPorcess = exec('java -jar C:\\Users\\devil\\eclipse-workspace\\invoke-jar.jar "Jar is invoked by Node js"', function(err, stdout, stderr) {
    if (err) {
        console.log(err)
    }
    console.log(stdout)
})

you can observe that callback function has three arguments like err, stdout, stderr.
err-> To handle the node js error, stdout -> To store the output from the java program, stderr-> It is for handling the java error.

Another js program named index.js, which contains

var exec=require('./executejar')

Command for execution,

node index

Output:

Jar is invoked by Node.js

 

You can get the whole code from the Github repo. Below is the link:

https://github.com/sahajahanAlli/invoke-jar-using-node-js

Please Install Node module to run:
Process:
  1. Navigate to the folder(queue-example) using command prompt/windows powershell
  2. Type command “npm install”. It will install node modules.
  3. Type command “npm start”. It will show the output.

Please feel free to comments or provide the suggestion.