I have a NodeJS/Express (4.10.2) function which calls an external subprocess through spawn:
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
var spawn = require('child_process').spawn;
var java = spawn("java", ['-cp', 'lib\\*;bin', 'com.my.app.App']);
...
}
What I'd like to do is add some kind of anonymous function which will get called when the page is changed, tab is closed, or even refreshed. In short, I'd like to kill the spawned process!
Google isn't being good to me in researching this.
What I would do is send a cookie with a unique value with every request, and store that value in a map as the key, with the value being the child process object so you can kill it.
Then add an unload handler on the page in Javascript to fire a request to a new URL with that unique value to allow you to do the killing.
e.g. your express code becomes something like:
var javaSessions = {
_counter: -1
};
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
var spawn = require('child_process').spawn;
var javaSessionId = javaSessions._counter++;
res.cookie('java_session_id', javaSessionId);
var java = spawn("java", ['-cp', 'lib\\*;bin', 'com.my.app.App']);
javaSessions[javaSessionId] = java;
...
});
app.get('/unload/:id', function (req, res) {
var java = javaSessions[req.params.id];
javaSessions[req.params.id] = null;
java.kill();
});
Then in index.html, add the following markup down the bottom (assuming you don't need to target browsers older than about Internet Explorer 8):
<script type="text/javascript">
window.onunload = function () {
var req = new XMLHttpRequest(),
javaSessionId = document.cookie.replace(/(?:(?:^|.*;\s*)java_session_id\s*\=\s*([^;]*).*$)|^.*$/, "$1"); // regex from https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie#Example_.232.3A_Get_a_sample_cookie_named_test2
req.open("GET", "/unload/" + javaSessionId);
};
</script>
You might also be able to get the cookie value from the request, instead of needing to explicitly read it in Javascript and send it as a URL parameter. It may already be sent with the request.
You will need to test all of this, this is all very hypothetical code you will have to try yourself.