I had to display node.js server side log on browser so I used socket.io and tail modules. The code is working fine except one issue. The issue is when first time i visit the page its display correct logs to me on the browser but when refresh the page then logs appears twice then again I refresh the page then it appears three time and so on. Here is my code
logs.ejs
<% script('/js/socket.io.js') -%>
<% script('/js/jquery.min.js') -%>
<script>
// creates socket on page load
$(function() {
var socket = null;
var streamer = null;
var socket = io.connect('http://localhost');
streamer = $('#streamer');
// outputs a new line to browser for each new line in file
socket.on('new-data', function(data) {
var newLine = $('<div>' + data.value + '</div>');
streamer.append(newLine);
});
});
</script>
<div id="streamer">
</div>
app.js
var app = express()
,server = require('http').Server(app)
,io = require('socket.io')(server)
server.listen(3000)
Tail = require('tail').Tail;
io.sockets.on('connection', function(socket) {
tail = new Tail("log.log"); // file to stream
tail.on('line', function(data) {
return io.sockets.emit('new-data', {
channel: 'stdout',
value: data
});
});
});
I dont know but I think its creating multiple connections on page refresh.