I'm new to javascript and nodeJS.
I'm having some trouble trying to run a SQL query to retrieve data using Nodejs.
I created a connection module (db.js) but unable to get the results from executing controller.js.
I know for sure that the connection module is working well as I manage to retrieve data from DB if I were to swap the resolve(connection) to queries.
Please help me take a look where did I go wrong.
Here is the db.js
var mysql = require('mysql2');
var Client = require('ssh2').Client;
var ssh = new Client();
var db = new Promise(function (resolve, reject) {
ssh.on('ready', function () {
ssh.forwardOut(
'127.0.0.1',
12345,
'127.0.0.1',
3306,
function (err, stream) {
if (err) throw err;
let connection = mysql.createConnection({
host: '127.0.0.1',
user: 'username',
password: 'password',
database: 'test',
stream: stream
});
connection.connect(function (err) {
if (!err) {
resolve(connection)
} else {
reject(err);
}
});
});
}).connect({
host: 'hostname',
port: 22,
username: 'username',
password: 'password'
});
});
module.exports = db;
Here is the controller.js
var database = require('./db');
module.exports.getcats = (function(req, res) {
database().then(function (connection) {
connection.query("SELECT * FROM listUnit", function (error, results, fields) {
if (error) {
console.log(error);
return;
}
res.write(results);
});
});
});