0

I am new to node.js, coming from java. Having a hard time understanding how to use or reuse a db connection on a number of different script files.

Following is a typical example:

var sql = require('mssql');
var config = {
  user: 'lib_user',
  password: 'lib_password',
  server: 'localhost',
  database: 'lib_db',
  options: {
     encrypt: true
  }
};
var connection = new sql.Connection(config, function(err) {
var request = new sql.Request(connection);
 request.query('select title from book', function(err, rs) {
    rs.forEach(function(row) {
    console.log(row.title);
});
});
});

connection.on('error', function(err) {
  console.log(err);
});

This works fine for accessing the db on a single page, what if the db needs to be accessed on 5 different .js files? How would one acquire the connection object on each script file?

Am I right in thinking I need to wrap the above code in a script file and that file should return the connection object and then the require(xyz) idiom should be used?

kmansoor
  • 4,265
  • 9
  • 52
  • 95
  • Can you not inject the db connection dependency into the javascript module that requires to know about it? http://stackoverflow.com/questions/7708194/dependency-injection-with-requirejs – widged Sep 08 '15 at 22:53
  • 1
    Singleton Pattern with Require JS https://gist.github.com/jasonwyatt/1106973 (best avoided) – widged Sep 08 '15 at 22:57

1 Answers1

1

You can do this

module.exports.connectionDB = connection

After that all you need to do is:

var connection = require('./mainAppFile').connectionDB;
BadVolt
  • 617
  • 1
  • 7
  • 19