How to return a JSON object from a mySQL query in node.js
<p>I'm very new to coding and node.js in particular so this is probably a dumb question - but all the examples I read for mySQL database queries end with just logging the query results to the console... what I want to do (or at least what I think I want to do) for my web application is return the query result as the product of a function so that I can allow my .ejs file to make use of the JSON object.</p>

<p>The situation as the moment is no matter what I try my .ejs file receives "Hello World" as the product of getDriver(). I want it to receive 'rows' (ie. the JSON object that my SQL query returns with)</p>

<p>I can see the JSON result in the console &amp; it looks perfect.. I just can't seem to make it 'exist' outside of the function :(</p>

<pre><code>var express = require('express');
var router = express.Router();
var mysql = require('mysql');
/* GET about page. */
router.get('/', function(req, res, next) {
    res.render('SQLtest', { title: 'SQL test',
                        result: getDriver() // I want this to be my JSON object
    });
});

module.exports = router;


function getDriver() {
    var result = "Hello World"; // my .ejs see's this
        var connection = mysql.createConnection(
            {
                host: 'localhost',
                user: 'root',
                password: 'password',
                database: 'my database',
                port: 3306
            }
        );

        connection.query("SELECT * FROM my_table",
            function (err, rows) {
                if (err) {
                console.log(err);
                }

                console.log(rows); // query result looks fine as JSON object
                result = rows; // now change "Hello World" to the JSON object
            }
        );
    return result; // however this still = "Hello World"  :(
}
</code></pre>