Node JS database callbacks

Pretty much all of the stuff I have seen related to data queries under nodejs are writing to the console rather than returning the complete data from the function.

I am struggling to retrieve the queried data, here's what I have now but it returns nothing:

function dbGet(req,res,cb){
    var sqlite3 = require('sqlite3').verbose();
    var db = new sqlite3.Database('/usr/share/csServ/csdb.sqlite');
    var json = []; var jrow = {};
    db.each("SELECT * from sensors", function(err,row) { jrow['id'] = row.id; jrow['tstamp'] = row.tstamp; json.push(jrow);}, cb(json) );
}

dbGet(req,res,function(json){
    console.log(json);
});

How can I get the data into my callback and how can I close the db db.close() in the dbGet() function as I don't know when the each loop is completed ?

If you want cb(json) as the complete callback, you'll need to wrap it in another function so it can wait to be evaluated:

db.each("SELECT * from sensors",
    function (err, row) { /* ... */ },
    function () { cb(json); }
);

As is, cb(json) is being called immediately, when json.length === 0, and its return value (currently undefined) is being passed to db.each().

You can also use this same function to close the connection:

db.each("SELECT * from sensors",
    function (err, row) { /* ... */ },
    function () {
        db.close();
        cb(json);
    }
);