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

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

Comments

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.