Last active
January 24, 2018 13:13
-
-
Save cleuton/10157340 to your computer and use it in GitHub Desktop.
Non blocker cpu intensive node script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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'); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A webworker sample.