Use function inside included javascript using require()

256 views Asked by At

In Node.js application, I am trying to use functions inside the javascript called on main js inside require(). Say as example, I have one js file which is database connectivity file and has functions those can be used in main javascript file. I have called require() for the database js file. Now with the variable in main js file, I want to use functions inside database js files, so I can reuse the conection object created in database js. I have read about module.exports but I didnt found the clear solution on this.

Please suggest how to achieve this.

1

There are 1 answers

0
Naeem Shaikh On

Yes you can reuse the connection object created in different file.

for ex. in your main.js file :

var db=require("./db.js");
 var pool  =db().pool;
console.log(pool);
app.get("/",function(req,res){
    console.log("get request");


               pool.getConnection(function(err, conn) {
    if(!err) {
              console.log("connection open home");
              var stmt="select pass from login";
               conn.query(stmt,function(err,rows){
                 if(err)
                 {
                     res.render('pages/dberr');
                 }
                 else{
                    if(rows.length>0)// data found in database
                        {


                    console.log("row[0].uname"+rows[0].uname);

                         res.render('pages/home',{user:"guest"});

                    }else{ 
                    res.render('pages/login');

                            }
                 }

               });
              }
              else{
                console.log("error occured"+err);
                 res.render('pages/login');
              }
            conn.release();

              console.log("connection released");
    });



});

here I am importing db.js file which returns me a property pool, which is assigned to my local variable pool in main.js file, now I can use at as usual.

and the db.js file

var mysql = require('mysql');
var db=function(){
    return{ 



        pool:  mysql.createPool({
  host     : process.env.IP,
  user     : process.env.C9_USER,
  password : '',
  port:3306,
  database: "node"
})



};
};

module.exports = db;

This works fine.