Wednesday, December 26, 2018

node.js - How to show data from mysql in nodejs with a refresh rate

I'd like to show data from MySQL using nodejs with a refresh rate. I've done the following coding and getting result. But the problem is if I open localhost:8000/?id=1 on the browser in one tab it's showing data from MySQL for id 1, but if I open localhost:8000/?id=2 on another tab, it shows data for id 2 but at the same time, the first tab begins to show data for id 2 also. I need to show data from MySQL for the specific id in URL on different tabs.



in server.js I wrote





var app = require('http').createServer(handler),
url = require("url"),
io = require('socket.io').listen(app),
fs = require('fs'),

mysql = require('mysql'),
connectionsArray = [],
connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'nodetest'
}),
POLLING_INTERVAL = 3000,
pollingTimer;

connection.connect(function(err) {
console.log(err);
});
app.listen(8000);
var id;
function handler(req, res) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
if (query.id) {
id = query.id;

console.log(id);
}
fs.readFile('client.html',
function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client.html');
}
res.writeHead(200);

res.end(data);
});
}
var pollingLoop = function() {
var query = connection.query('SELECT * FROM users WHERE id = ' + id),
users = [];
query.on('error',
function(err) {
console.log(err);
updateSockets(err);

}).on('result',
function(user) {
users.push(user);
}).on('end',
function() {
if (connectionsArray.length) {
pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);
updateSockets({
users: users
});

}
});
};
io.sockets.on('connection',
function(socket) {
console.log('Number of connections:' + connectionsArray.length);
if (!connectionsArray.length) {
pollingLoop();
}
socket.on('disconnect',

function() {
var socketIndex = connectionsArray.indexOf(socket);
console.log('socket = ' + socketIndex + ' disconnected');
if (socketIndex >= 0) {
connectionsArray.splice(socketIndex, 1);
}
});
console.log('A new socket is connected!');
connectionsArray.push(socket);
});

var updateSockets = function(data) {
data.time = new Date();
connectionsArray.forEach(function(tmpSocket) {
tmpSocket.volatile.emit('notification', data);
});
};



And in client.html i wrote












Loading ...



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...