Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a jar file with node.js child_process API?

Tags:

I tried to run a jar file on nodejs but it threw out a following error:

Error: Unable to access jarfile /home/example/Applications/example.jar

This is the following code that I have in my test.js:

var exec = require('child_process').exec, child;
child = exec('/usr/bin/java -jar ~/Applications/example.jar',
  function (error, stdout, stderr){
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if(error !== null){
      console.log('exec error: ' + error);
    }
});

I ran my test.js with nodejs in this command but received the error above:

node test.js

Is there any mistake that I made with my code? I am not sure why it is throwing an error at this point.

like image 258
Jonathan Moo Avatar asked Oct 15 '12 08:10

Jonathan Moo


People also ask

How do I run a .JAR file?

To run an application in a nonexecutable JAR file, we have to use -cp option instead of -jar. We'll use the -cp option (short for classpath) to specify the JAR file that contains the class file we want to execute: java -cp jar-file-name main-class-name [args …]

How do I run a node JS terminal?

Node. js can run shell commands by using the standard child_process module. If we use the exec() function, our command will run and its output will be available to us in a callback. If we use the spawn() module, its output will be available via event listeners.


2 Answers

remove .jar from exec();

java will find the jar file without .jar when using the -jar argument. else its like.. searching for filename.jar.jar

special snowflake macos requires the .jar and does not work if you omit it.
(thanks to Gʀɪᴍ) he also created a related question

like image 126
GottZ Avatar answered Sep 20 '22 12:09

GottZ


If you are using it on windows command prompt you can use this code.

var exec = require('child_process').exec, child;
child = exec('java -jar C:\\..\\..\\yourjar.jar',
function (error, stdout, stderr){
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if(error !== null){
  console.log('exec error: ' + error);
}
});

Dont forget the double slaces or else it will be a mess.

like image 33
Coding bat Avatar answered Sep 17 '22 12:09

Coding bat