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?