I'm retrieving data from mysql db and I need to send data to render in my ejs file.
router.get('/', function(req, res, next) {
res.render('index', { speedAccelData: getSpeedAccelData() });
});
module.exports = router;
Following is the function which I used to get data from database. It successfully prints jsonStr
with required data. I need to return jsonStr
from the function.
var getSpeedAccelData = function () {
var jsonStr;
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "db_name"
});
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
});
con.query('SELECT * FROM table_name',function(err, result){
if(err) throw err;
jsonStr = JSON.stringify(result)
console.log(jsonStr);
});
con.end();
};
How can I return query data to render?