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?

2

1 Answer 1

1

You can do this

module.exports.connectionDB = connection

After that all you need to do is:

var connection = require('./mainAppFile').connectionDB;
Sign up to request clarification or add additional context in comments.

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.