I am new to node.js and having a problem with a mysql query. I have coped code from this SO answer but it's still giving me 'undefined' as the browser result, instead of the rows from the database. The console prints 'got rows' so the query itself seems to have been successful.
var http = require('http');
var mysql = require('mysql');
var sql = require('./sqltest');
var pool = mysql.createPool({
connectionLimit : 100,
host: "my.host",
port: '3306',
user: "me",
database: 'db_name',
password: "pw"
});
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("Library is: " + sql.getLibrary(pool) );
res.end("....done. ");
}).listen(8080);
and here is the code (sqltest.js) that I have copied / modified from the link :
var pool;
function executeQuery(query, callback) {
pool.getConnection(function (err, connection) {
if (err) {
return callback(err, null);
}
else if (connection) {
connection.query(query, function (err, rows, fields) {
connection.release();
if (err) {
return callback(err, null);
}
return callback(null, rows);
})
}
else {
return callback(true, "No Connection");
}
});
}
function getResult(query,callback) {
executeQuery(query, function (err, rows) {
if (!err) {
callback(null,rows);
}
else {
callback(true,err);
}
});
}
function getLibrary(sqlpool) {
pool = sqlpool;
getResult('select * from Library', function (err, rows) {
if (err)
{
console.log(err);
return 'db error';
}
else {
console.log("got rows");
return JSON.stringify(rows);
}
});
};
exports.getLibrary = getLibrary;