0

I have a two files a server.js and an sqlHelper.js. The server sets up a socket connection with a web browser and retrieves a row number that it then forwards to sqlHelper. Relevant code snippets below:

server.js

//Setup websocket connection with browser
var ws = require("nodejs-websocket")
var server = ws.createServer(function (conn) {
 console.log("Connected")
 conn.on("text", function (str) {

    var select = require('./sqlHelper.js');
     select.query(str, returnVal);

   //this returns object Object
   function returnVal(res){
   console.log("Got it red:"+res);
    }
  conn.on("close", function (code, reason) {
    console.log("Connection terminated")
   })

}).listen(7001)

sqlHelper.js

exports.query = function(res, conn){
   var mysql = require('mysql');
   var connection = mysql.createConnection({

    host: 'localhost',
    user: 'root',
    password: '******',
    database: '*******'
    });
  connection.connect();
  connection.query('select red, green, blue, c1, c2 from table 
   where   ID    ='+res, function(err, result){
   if(err){
    console.error(err);
    return;
   }
     console.log(result);
     //return result;
  });
};

//this returns the correct information
exports.returnVal=function(res){
  console.log(res);
}

When I write to console from a method within SQLHelper.js the value is correct, but when I use the same method in server.js I get object Object.

I'm not sure my approach is correct. I'm confident that the answer involves callbacks, but I'm not sure why my data is displaying differently between these two pieces of js.

Thanks in advance!

David Ryan
  • 109
  • 1
  • 1
  • 7

1 Answers1

0

This is asynchronous and thus firstly you need a callback to the query function to return the result. Otherwise, you may not get the proper result back. ALso, the result will be an array, so result[0].red , result[0].green , etc would be the way you access the column values.

SKY
  • 240
  • 1
  • 7