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.
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 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.
Explanation. By default, npm installs any dependency in the local mode.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With