ExpressJS - Guide3

expressjs

What is this application about?

Express is the most popular web framework for Node, while Socket.IO is a realtime framework that enables bi-directional communication between web clients and the server. We are going to create a basic tracking pixel application using the two that has a dashboard which reports realtime visits.

Besides Express and Socket.IO we will need to install the emptygif module. When the user visits http://localhost:1337/tpx.gif, a message will be sent to all the users that are viewing the homepage. The message will contain information related to the clients, mainly their IP address and user agent.

Code for the server.js file:

var emptygif = require('emptygif');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);

app.get('/tpx.gif', function(req, res, next) {
  io.emit('visit', {
    ip: req.ip,
    ua: req.headers['user-agent']
  });

  emptygif.sendEmptyGif(req, res, {
    'Content-Type': 'image/gif',
    'Content-Length': emptygif.emptyGifBufferLength,
    'Cache-Control': 'public, max-age=0' // or specify expiry to make sure it will call everytime
  });
});

app.use(express.static(__dirname + '/public'));

server.listen(1337);

Now on the frontend all we have to do is listen for that 'visit' event emitted by the server and modify the UI accordingly, like so:

<!DOCTYPE HTML>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Realtime pixel tracking dashboard</title>
  <style type="text/css">
    .visit {
      margin: 5px 0;
      border-bottom: 1px dotted #CCC;
      padding: 5px 0;
    }
    .ip {
      margin: 0 10px;
      border-left: 1px dotted #CCC;
      border-right: 1px dotted #CCC;
      padding: 0 5px;
    }
  </style>
</head>
<body>
  <h1>Realtime pixel tracking dashboard</h1>

  <div class="visits"></div>

  <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.1/moment.min.js"></script>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    $(function() {
      var socket = io();
      var containerEl = $('.visits');

      socket.on('visit', function(visit) {
        var newItem = '<div class="visit">';
        newItem += '<span class="date">' + moment().format('MMMM Do YYYY, HH:mm:ss') + '</span>';
        newItem += '<span class="ip">' + visit.ip + '</span>';
        newItem += '<span class="ua">' + visit.ua + '</span></div>';
        containerEl.append(newItem);
      });
    });
  </script>
</body>
</html>

Now start up the application, open the dashboard in a tab and the tracking pixel URL in different browsers.

See the bottom of https://www.airpair.com/javascript/node-js-tutorial

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License