1

I've got two node.js files: server.js and database.js. I want my socket.io emitting to happen in server.js and the database queries in database.js. Server.js:

// init
io.sockets.on('connection', function(socket) {
    initdb = db.initdb();
    console.log(initdb)
});

My database.js contains basically the following code:

function query(queryString) {
    connection = mysql.createConnection({
        host: '12.23.45.67',
        user: 'user',
        password: 'password',
        database: 'database'
    });

    connection.connect();

    var res = connection.query(queryString, function(err, rows, fields) {
        if (err) throw err;
    });

    connection.end();
}


// export initdb for external usage by server.js
exports.initdb = function() {
    var initdb = query("SELECT * FROM columns;");
};

My problem is that I want the rows object from within the connection.query function to be returned to my initdb function. However the only place where I can log this object is within that function. How can I pass the query results so I can emit the JSON object it from server.js?

1 Answer 1

6

Remember that node is asynchronous. So for the most part, you get data back through callbacks rather than as return values to functions.

You'll need to chain a callback through to where your query happens, something like:

// in database.js
exports.initdb = function(cb) {
  query("SELECT * FROM columns", cb)
}

function query(queryString, cb) {
  // .. stuff omitted

  var res = connection.query(queryString, function(err, rows, fields) {
    connection.end();
    if (err) return cb(err);
    cb(null,rows);
  });

// in server.js
io.sockets.on('connection', function(socket) {
  db.initdb(function(err,rows) {
    if (err) {
      // do something with the error
    } else {
      console.log(rows)
    }
  });
});

The callback would be a function taking 2 parameters, err and rows. Your server.js code would need to check the value of err and act accordingly, otherwise it would have the rows.

Sign up to request clarification or add additional context in comments.

2 Comments

It's my first node.js project ever. Didn't get this essential part. Thanks a lot juanpaco!
Hey, you bet. We've all been there. :) If you're just learning, you may find some value in a screencast series I do at learnallthenodes.com. Whether you check it out or not, happy coding!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.