Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Java program from NodeJs [duplicate]

Tags:

java

node.js

I have a Java program that I normally start from command line. After starting from command line, the java program keeps running forever until Ctrl+C is pressed to quit it or kill command from another script. The Java program outputs error messages if any to the console.

Now I want to develop express based NodeJs web application. When the user clicks on a link (Run) , the click handler will invoke Ajax request which will cause the backend NodeJs script to run this Java program if it is not already running. Another link (Stop) will make Ajax request to stop this Java program.

How this can be achieved? Answer with sample code will be most useful.

Also there is a requirement: if this NodeJs web application is terminated, the Java program that was started by it, keeps running i.e. it is not dependent on NodeJs web application.

like image 411
rjc Avatar asked Sep 15 '13 18:09

rjc


People also ask

Can we write Java code in node JS?

Node. js is an event-driven JavaScript runtime platform that is built using the Chrome's V8 JavaScript engine. Node is mainly used for building large-scale applications. In this article, we will see how to run a Java code in Node.

What is a Java node?

What is a Node. An Individual Node in java is a class that is used to create the individual data holding blocks for various data structures, which organize data in a nonsequential fashion.

What is the default mode in which NPM installs a dependency?

Explanation. By default, npm installs any dependency in the local mode.


1 Answers

You can start a child process, and send a kill signal when you don't need it.

var spawn = require('child_process').spawn;
var child = spawn('java', ['params1', 'param2']);

To kill the application, or to simulate a CTRL+C, send a signal:

// control + c is an interrupt signal
child.kill('SIGINT');

// or send from the main process
process.kill(child.pid, 'SIGINT');

If you're going to run the application detached, you should probably write the PID somewhere. To run the application detached, run it like this:

var fs = require('fs');
var out = fs.openSync('./out.log', 'a');
var err = fs.openSync('./out.log', 'a');

var child = spawn('java', [], {
  detached: true,
  stdio: [ 'ignore', out, err ]
});
child.unref();

This spawns a child process whose I/O streams aren't associated with the parent process.

like image 107
hexacyanide Avatar answered Oct 03 '22 00:10

hexacyanide