I have an Express server that provides some computations as web services.
Computation time ranges from <1s to 10s.
Is there a way to stop the execution of a request-handling function (which is one of these computations) when a new request comes in ?
Basically, the question is : is there a way to stop the execution of a function in Javascript? If not, is there a way I could terminate the thread that process the Express request ? If not, what would you suggest ?
You can't. JavaScript, including Node.js, is inherently single-threaded. If a CPU-bound function is running, nothing can interrupt it.
A better way of running these computations would be to fork another process to run them, which can then be stopped. For example:
fibo.js
function fibo(n) { // intentionally naive cpu-bound computation
return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1;
}
process.on('message', function(n) {
process.send(fibo(n));
});
server.js
var http = require('http'), cp = require('child_process');
var fibo;
http.createServer(function(req, res) {
if(fibo) {
fibo.kill();
fibo = null;
res.end('terminated');
} else {
fibo = cp.fork('./fibo.js');
fibo.on('message', function(n) {
res.end(n);
});
fibo.on('exit', function() {
res.end('terminated by other request');
});
fibo.send(50);
}
}).listen(8000);
This is just an example. Please don't use as-is. This server can only handle one concurrent request actually calculating something, and child_process.fork
is not lightweight.