Monday, 1 May 2017

node.js help understanding example code

I'm working on a school project that requires me to use Node.js. Right now I'm just looking at the example code I'm given and I was wondering if anyone could explain to me exactly how the relationship between these to js files works: first:

var util = require('util');
var path = require('path');
var http = require('http');
var fs   = require('fs');
var server = http.createServer();

// attach handler
server.on('request', function (req,res) {
  var file = path.normalize('.' + req.url);

  fs.exists(file, function(exists) {
    if (exists) {
      var rs = fs.createReadStream(file);

      rs.on('error', function() {
        res.writeHead(500); // error status
        res.end('Internal Server Error');
      });


      res.writeHead(200); // ok status

      // PIPE the read stream with the RESPONSE stream
      rs.pipe(res);
    } 
    else {
      res.writeHead(404); // error status
      res.end('NOT FOUND');
    }
  });

}); // end server on handler

server.listen(4000);
console.log("hi");
console.log("hi");
console.log("hi");
console.log("hi");

The second one:

var io = require('socket.io').listen(5000);

io.sockets.on('connection', function(socket) {
  socket.on('myEvent', function(content) {
    console.log(content); 
    socket.emit('server', "This is the server: got your message");
    var num = 3;
    var interval = setInterval( function() {
        socket.emit('server', num + ": message from server");
        if (num-- == 0) { 
          clearInterval(interval); // stops timer
        }
    }, 1000); // fire every 1 second
  });
});

I understand that the first one receives the connection from the client and passes it onto the second which executes the code, but I'm not sure how exactly this is happening or why it's necessary.



via Alex5775

No comments:

Post a Comment