barzik

Alternative to https://github.com/barzik/example-nodejs-cloc

Oct 4th, 2014
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2. Creating the server object. launch the createServer method and the handler as the callback.
  3. The handler is being fired rght after
  4. **/
  5. var app = require('http').createServer(handler)
  6. var io = require('socket.io')(app);
  7.  
  8. var fs = require('fs'); //We need fs to call index.html
  9. var port = process.env.PORT || 3000;
  10.  
  11. app.listen(port); //Listening on port 80. change it to 3000 if you have Apache on local machine
  12.  
  13. /**
  14. Callback that fired when http.createServer completed
  15.  
  16. var req = the request.
  17. var res = the result.
  18. **/
  19. function handler (req, res) {
  20.   fs.readFile(__dirname + '/index.html', //reading the file
  21.   function (err, data) {  //calback that get fired right after the file was created
  22.     if (err) { //if callback return error.
  23.       res.writeHead(500);
  24.       return res.end('Error loading index.html');
  25.     }
  26.  
  27.     res.writeHead(200); //returning 200
  28.     res.end(data); //printing the data - the index.html content
  29.  
  30.     /** replaced part **/
  31.     var clockInterval = setInterval(function(){ //running it every second
  32.     var current_time = getCurrentTime(); //calculating the time
  33.       io.sockets.emit('clock-event', current_time); //emitting the clock-event through the socket
  34.     },  1000);  
  35.     /** replaced part **/
  36.    
  37.   });
  38. }
  39.  
  40.  
  41.  
  42. /** function for printing the hour. Taken from
  43. http://www.mcterano.com/blog/%D7%A0%D7%99%D7%A1%D7%95%D7%99-17-%D7%A9%D7%A2%D7%95%D7%9F-%D7%A9%D7%9E%D7%AA%D7%A2%D7%93%D7%9B%D7%9F-%D7%91%D7%96%D7%9E%D7%9F-%D7%90%D7%9E%D7%AA-%D7%91%D7%A2%D7%96%D7%A8%D7%AA-node-js/
  44. **/
  45.  
  46. function getCurrentTime(){
  47.     var currentDate = new Date();
  48.     var currentHours = addZeroToOneDigit(currentDate.getHours());
  49.     var currentMinutes = addZeroToOneDigit(currentDate.getMinutes());
  50.     var currentSeconds = addZeroToOneDigit(currentDate.getSeconds());
  51.     var currentTime = currentHours + ":" + currentMinutes + ":" + currentSeconds;
  52.     var html = parseHtml(currentTime);
  53.     return html;
  54. }
  55.  
  56. function addZeroToOneDigit(digits){
  57.     var result = ((digits).toString().length === 1) ? "0" + digits : digits;
  58.     return result;
  59. }
  60.  
  61. function parseHtml(currentTime){
  62.     var result = '<p style="direction: rtl; font: 12px Tahoma">';
  63.     result += 'השעה כרגע היא: ' + currentTime;
  64.     result += '.</p>';
  65.     return result;
  66. }
Add Comment
Please, Sign In to add comment