Search code examples
javascriptjsonnode.jssocket.ionode-mysql

Node.js / Socket.io / Mysql to print as JSON


SOLVED: Answer is: socket.on('clients', function(data) { document.write(JSON.stringify(data)); });

I want to get ouput like this (only the part in bold) on the screen as JSON:

debug - websocket writing 5:::{"name":"clients","args":[[{"id":6,"name":"demo 3"},{"id":7,"name":"demo1"}]]}

I must be missing something cause I just can't understand why it doesn't print as JSON. I have 3 files:

app.js (server) :

var fs = require('fs');
var db = require("./db.js");

var http = require('http').createServer(function handler(req, res) {
    fs.readFile(__dirname + '/index.html', function (err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Error loading index.html');
        } else {
            res.writeHead(200);
            res.end(data);
        }
    });
}).listen(3000);
// -----------------------------------
var io = require('socket.io').listen(http);
io.sockets.on('connection', function (client) {
    console.log('Client connected');
    db.get_employees(function (employees) {
        io.sockets.emit('clients', employees);
    });
});

db.js (connect to database) :

// -----------------------------------
var mysql = require('mysql');
var client = mysql.createConnection({
    user: 'xxxx',
    password: 'yyyy',
    host: '123.45.67.89',
    database: 'zzzz'
});
// -----------------------------------
exports.get_employees = function (callback) {
    client.query("select id, name from clients", function (err, results, fields) {
        callback(results);
    });
}

And index.html :

<script src="http://192.168.2.25:3000/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script>
 $(document).ready(function() {
  var socket  = io.connect('http://192.168.2.25:3000');
  socket.on('clients', function(data) {
   $.each(data, function(i, obj) {
        //  document.write(obj);      // Gets me [object Object][object Object]
        //  document.write(obj.name)  // Gets me name column
        //  document.write(obj.email) // Gets me email column
        //  document.write(obj.xxxxx) // Gets me xxxxx column
        //  document.write(JSON.stringify(obj));   //Prints as JSON but structure is   wrong and it is a html string not as JSON output

     });
  });
});
</script>

I am having trouble figuring why I cannot print it as JSON. See index.html commented lines. As well I want it to be a clean JSON output of my database and not as html.

The io.sockets.emit('clients', employees); in the App.js emits a correct json format I want but I can't get it outputted.I get [Object Object] or Undefined. There must be a way to do it because if I have to structure it manually it would make it speed inefficient.

Any help would be appreciated.


Solution

  • It's because you're outputting each JSON object on it's own. Try doing stringify on the "data" variable e.g.

    $(document).ready(function() {
      var socket  = io.connect('http://192.168.2.25:3000');
      socket.on('clients', function(data) {
        document.write(JSON.stringify(data));
      });
    });