I want to write a nodejs program that computes factorial of all numbers less than 30 which is very popular among new programmers.
fact(0) = 1
fact(i) = i*fact(i-1)
But this time I want the nodejs to print the output online on the web browser of the client.
I know how to write the code for factorial, but I don't know how to update the clients view whenever a new factorial number is computed.
First of all processor intensive tasks should be done on other processes. That's because doing so in your node HTTP server will block the main event loop!
You can do the calculation on other process(es) and transfer the results to your node.js server process via standard streams, sockets, a database, etc.
My personal opinion is, node.js is not the right tool for doing such calculation (I'm being convinced that it might work for small numbers)
This article on Heroku walks you through Building a Real-time, Polyglot Application with Node.js, Ruby, MongoDB and Socket.IO.
> I just want to know how to show my output to the client whenever something happens:
In order to do this with socket.io, you need to install it first:
npm install socket.io
Then in your node application:
Note that in this example, I'm pushing a message to clients on an interval.
var http = require('http'),
io;
var html = "<!doctype html>" +
"<title>Socket.IO Example</title>" +
"<div id=\"number\"></div>" +
"<script src=\"/socket.io/socket.io.js\"></script>" +
"<script>" +
"var socket = io.connect()," +
"numberElement = document.getElementById('number');" +
"socket.on('message', function (data) {" +
//"numberElement.innerText = data;" +
"numberElement.innerHTML = data;" +
"});" +
"</script>";
var server = http.createServer(function (request, response) {
response.statusCode = 200;
response.setHeader('Content-Type', 'text/html');
response.end(html);
});
server.listen(8080);
io = require('socket.io').listen(server);
function push(socket) {
var i = 0;
return function () {
socket.send(String(i++ % 3600));
};
}
io.sockets.on('connection', function (socket) {
var interval = setInterval(push(socket), 1000);
socket.on('disconnect', function () {
clearInterval(interval);
});
});