How to Execute a .jar File with Node.js Child Processes

You probably have already come across situations where your application had to execute other applications or native commands from the OS. Node.js can easily do that by spawning child processes. To show you how to do that I’m going to give you an example of how to execute a .jar file with node.

First let’s create a very simple java application for us to use in this example, this is the one I’m going to use:

package javaapp;
public class JavaApp{
    public static void main(String[] args) {
        System.out.println("This is the Java application output!!");

This class is very simple but it will be enough to demonstrate how child processes work, just copy the code, compile it, and place the jar file into folder of your choice.

Now let’s create a js file containing the following code:

var exec = require('child_process').exec;
var child = exec('java -jar C:/javaApp.jar',
  function (error, stdout, stderr){
    console.log('Output -> ' + stdout);
    if(error !== null){
      console.log("Error -> "+error);
module.exports = child;

Note how easy it is, first I required the module child_process and then I called the function exec() passing as an argument a native OS command to execute a java file, which is : java -jar C:/javaApp.jar. In the callback function I have 3 variables: error, stdout, stderr, but I’m going to use only the first two. The javaApp.jar output will be stored on the stdout variable, and the errors will be in the error variable, obviously.

To run this code just open the terminal, navigate to your js file location and execute the command:

node app.js

If everything is right you should see the output:

Output -> This is the Java application output!!

Recommended for you

4 comments on “How to Execute a .jar File with Node.js Child Processes

    1. Michal

      In you java main class you have argument String[] args. This argument stores String that you have put as a argument on run. You can grab it and do whatever you want with it:

      public static void main(String[] args) {


      var child = exec('java -jar C:/javaApp.jar Hello World! it is a nice day', ...


      Output -> Hello World! it is a nice day
  1. vanshaj

    can anyone please suggest how will I host a webApp having this code, online. As the online console can only have nodejs console or java console (I think.).

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>