title: How to import mysql connection in another file in nodejs?
body: <p>I am not able to import the mysql connection file from the parent file to another file for making a DB connection.</p>
  
  <p>I can connect to DB if the query is written in same file, if i try to hit the same query in another file then i get "TypeError: connection.query is not a function" error. Not able to access any functions of the connection object.</p>
  
  <p>this is my server.js file:</p>
  
  <pre><code>var express = require('express');
  var cors = require('cors');
  var mysql = require('mysql');
  app = express(),
  app.use(cors()),
  port = process.env.PORT || 3001;
  bodyParser = require('body-parser');
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(bodyParser.json());
  config = {
      host: 'localhost',
      user: 'root',
      password: '',
      database: '&lt;DB name&gt;'
  }
  var connection = mysql.createConnection(config);
  
  connection.connect(function(err){
      if (err){
          console.log('error connecting:' + err.stack);
      }
      console.log('connected successfully to DB.');
  });
  
  
  var routes = require('./api/routes/routes'); //importing route
  routes(app);
  console.log('todo list RESTful API server started on: ' + port);
  app.listen(port);
  
  module.exports= connection;
  </code></pre>
  
  <p>This is my api.js file:</p>
  
  <pre><code>'use strict';
  var connection = require('../../server.js');
  
  connection.query ('select * from &lt;table name&gt;', function(error, results){
      if (results){
          console.log(results);
      }
      else{
          console.log(error);
      }
  });
  or
  exports.get=function(req,res){
          console.log(req.query.printerModel);
          console.log('inside get function');
          connection.query('select * from inkdetails', function(error, results){
              if (results){
                  res.status(200).send(inkdetails)
                  console.log(results);
              }
              else{
                  res.status(400).send(error)
                  console.log(error);
              }
          });
      };
  </code></pre>