You're posting the result of your work function to the worker. Put that function inside the web worker and then call it during onmessage.
var worker = new Worker(function(){
function work(n){
var res;
for (var i = 0; i < n; i++){
res += i * i * i;
}
return res;
}
onmessage = function(event) {
var result = work(event.data)
postMessage(result);
self.close();
};
});
You are doing all your heavy lifting on the server side, you want to put the work in the workers. You're blocking the entire server thread with having your work on the main thread.