Created
January 20, 2015 02:40
-
-
Save Squiva/0eabc2ca5080fd2e4de5 to your computer and use it in GitHub Desktop.
In this gist, I demonstrate how to make a system that counts how many people viewed your website using Node.js. Before you start coding, you want to type the following into your Kernel: npm install --save express and npm install --save socket.io
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
var app = require('express')(); | |
var http = require('http').Server(app); | |
var net = require('socket.io')(http); | |
var views = 0; | |
app.get('/', function(req, res) { | |
res.sendFile(__dirname + '/chat.html'); | |
}); | |
http.listen(3000, function() { | |
console.log("Loaded!"); | |
}); | |
net.on('connection', function() { | |
views++; | |
net.emit('chat message', views); | |
}); |
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
<html> | |
<head> | |
<title>Views</title> | |
</head> | |
<style> | |
#msgs {list-style-type: none; background: #99CCFF} | |
</style> | |
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> | |
<script src="http://code.jquery.com/jquery-1.11.1.js"></script> | |
<script> | |
$(document).ready(function() { | |
var socket = io(); | |
socket.on('chat message', function(msg) { | |
$('.new').remove(); | |
$('#msgs').append($('<li class="new">').text(msg + " views")); | |
}); | |
}); | |
</script> | |
<body> | |
<center> | |
<ul id="msgs"></ul> | |
</center> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment