Search code examples
javascriptnode.jseventsnode-modulestedious

Can Tedious connection and request event listeners be put in a separate module for Node.js?


This is my first ever question on here so please excuse any abnormalities in etiquette.

I am new to Node.js and backend programming in general. Right now I am using Node and Tedious to connect to a local SQL server. I'd like to keep my main.js file clean and so am trying to put everything related to my SQL connection in a separate js file. Below would be the simplest possible form I have for my main.js.

var http = require('http');
var sqlmodule = require('./SQLconnection');
http.createServer(function (req, res) {
  sqlmodule.makeConnection();
}).listen(8080);

I then have my SQLconnection.js file.

var Connection = require('tedious').Connection;
exports.makeConnection = function () {
  var config = {
      userName: 'XXXXXX',
      password: 'XXXXXX',
      server: 'XXXXXX'
  };
  var connection = new Connection(config);
};

//The below code is my event listener but I don't know how 
//to incorporate it as part of the module.
connection.on('connect', function(err) {
  if (err) {
     console.error('Connection error', err);
  } else {
     console.log('Connected');
  }
});

I have no problems when the listener isn't present in the file, but I can't find a way to have it part of the SQLconnection.js module. I've tried adding exports and module.exports before it in a few ways but to no success. It listening for an event and not being a normal function is stumping me.

How would I go about getting the event listeners in the separate file? I'm also trying to go about this as vanilla as possible, so I'm just using Node.js and Tedious at this point.


Solution

  • change

    exports.makeConnection = function () {
    

    to

    function makeConnection() {
    ...
    module.exports = {makeConnection}
    

    As an additional change, you need to put your connection listener in the sames scope as the connection variable. Personally, I would also have makeConnection return a Promise with the connection so you are not operating on a connection that has failed/not yet connected. Something like

    var Connection = require('tedious').Connection;

    function makeConnection() {
      var config = {
          userName: 'XXXXXX',
          password: 'XXXXXX',
          server: 'XXXXXX'
      };
      return new Promise((resolve, reject) => {
        var connection = new Connection(config);
    
        connection.on('connect', function(err) {
          if (err) return reject(err);
          resolve(connection);
        });
      }
    };
    module.exports = {makeConnection}