0

//Connection.js (module) that is require.

var mysql = require ('mysql');

var con ;
con = mysql.createConnection ({
       host : 'localhost',
       user : 'root' ,
       password : 'root',
       database : 'mydb'
});


exports.con = con;

module.exports  = con.connect ( function (err) {
        if (err) throw err;
        console.log("Connected!");
    });

//controller.js

var connection = require ('./connection'); var mysql = require ('mysql');

console.log(connection.con);
var sql = "Select * from user;";
connection.con.query(sql , function (err,result) {
    if(err) throw  err;
    console.log(result);
});

when I run the connection.js with the same query it works but when using the module in controller.js it gives me the error. //error code

TypeError: Cannot read property 'con' of undefined

Farhan Yaseen
  • 2,507
  • 2
  • 22
  • 37

2 Answers2

0

Your first attempt is almost right. Except,

module.exports  = con.connect ( function (err) {
  if (err) throw err;
  console.log("Connected!");
});

By doing that, you are replacing, exports with con.connect() call response, which overwrites previously assigned con property. If you remove that, you should be okay!

var mysql = require ('mysql');

var con ;
con = mysql.createConnection ({
  host : 'localhost',
  user : 'root' ,
  password : 'root',
  database : 'mydb'
});


exports.con = con;

con.connect ( function (err) {
  if (err) throw err;
  console.log("Connected!");
});

For reference check this(shared by @Aky_0788).

explorer
  • 944
  • 8
  • 18
0
//Connection.js (module) that is require.

var mysql = require ('mysql');

var con ;
con = mysql.createConnection ({
     host : 'localhost',
     user : 'root' ,
     password : 'root',
     database : 'mydb'
});

con.connect ( function (err) {
        if (err) throw err;
        console.log("Connected!");
});

exports.con = con;

controller.js

var connection = require ('./connection');
var mysql = require ('mysql');
console.log(connection.con);
var sql = "Select * from user;";
connection.con.query(sql , function (err,result) {
    if(err) throw  err;
    console.log(result);
});
Farhan Yaseen
  • 2,507
  • 2
  • 22
  • 37