A
A
Artur Yalaltdinov2016-07-22 22:46:34
Node.js
Artur Yalaltdinov, 2016-07-22 22:46:34

How to properly send data in json to node.js client?

Hello everyone, I have a question. I want to update the news feed on socket.io, but the question arose of how to give it all in json format? and which is better to use pool or static sql?
here is server.js code

var io = require('socket.io').listen(3000),
  mysql = require('mysql');

var pool  = mysql.createPool({
  	host            : 'localhost',
  	user            : 'root',
  	password        : '',
  	database        : 'test',
  port			: 3306
});
// Навешиваем обработчик на подключение нового клиента
io.sockets.on('connection', function (socket) {
  var time = (new Date).toLocaleTimeString();
  // Посылаем клиенту сообщение о том, что он успешно подключился
  socket.json.send({'event': 'connected', 'time': time});
  setInterval(function() {
    socket.broadcast.json.send(updateFeed());
  }, 5000);
});
function updateFeed() {
  pool.getConnection(function(err, connection) {
    connection.query('SELECT `u`.`member`, `u`.`login`, `n`.`text`, `n`.`time` FROM `news` as `n` LEFT JOIN `members` as `u` ON (`u`.`member` = `n`.`member_id`) ORDER BY `n`.`n_id` DESC LIMIT 0, 5', function(err, rows) {
      var gdata = "";
      [rows].forEach(function(item, key, rows){
        for(var index in item)
        {
if(item.hasOwnProperty(index)) {
          gdata += {
            index: item[index]
          };
}
        }
      });
      return gdata;
      connection.release();
      });
  });
};

and client code
socket = io.connect('localhost:3000');

    socket.on('connect', function () {
        socket.on('message', function (msg) {
            console.log(msg);
    });
  });

the matter is that it gives me null. What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
#
#algooptimize #bottize, 2016-07-22
@crazy_str

var gdata = "";
gdata += { add an object to the line??? gets a line
index: item[index]
};
socket.broadcast.json.send(updateFeed() returns a string, expects an object);

S
SagePtr, 2016-07-23
@SagePtr

Mixing asynchronous functions with synchronous ones.
updateFeed will not return anything, because it will finish before the asynchronous functions in it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question