Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Non blocker cpu intensive node script
// nonblocker.js
var restify = require('restify');
var fs = require('fs');
var Worker = require('webworker-threads').Worker;
var server = restify.createServer();
// Home page:
server.get('/',function(req, res) {
var bodyHtml = '<!DOCTYPE html><html><head><title>'
+ 'Teste Node.js - O Bom Programador</title></head>'
+ '<body>'
+ '<br/>Ok, agora, <a href="/blocker">o blocker</a>';
bodyHtml += '</code></pre></body></html>';
res.writeHead(200, {
'Content-Length': Buffer.byteLength(bodyHtml),
'Content-Type': 'text/html'
});
res.write(bodyHtml);
res.end();
});
// Blocker page:
server.get('/blocker',function(req, res) {
var worker = new Worker(function() {
onmessage = function (event) {
var fibonacci = function (n) {
if (n < 2)
return 1;
else
return fibonacci(n-2) + fibonacci(n-1);
};
postMessage(fibonacci(event.data));
}
});
worker.onmessage = function (event) {
var bodyHtml = '<!DOCTYPE html><html><head><title>'
+ 'Teste Node.js - O Bom Programador</title></head>'
+ '<body>';
var resultado = event.data;
bodyHtml += '<br/>' + resultado;
bodyHtml += '</code></pre></body></html>';
res.writeHead(200, {
'Content-Length': Buffer.byteLength(bodyHtml),
'Content-Type': 'text/html'
});
res.write(bodyHtml);
res.end();
};
worker.postMessage(45);
});
// Start server
server.listen(8080, function() {
console.log('Online: 8080');
});
@cleuton

This comment has been minimized.

Copy link
Owner Author

cleuton commented Apr 8, 2014

A webworker sample.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.