2

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.

Mario Gju
  • 23
  • 3

1 Answers1

1

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}
Deadron
  • 5,135
  • 1
  • 16
  • 27
  • For clarification, if I have multiple functions (like one for the connection and another for the request), would I have a module.exports={functionName} line at the bottom for each one? – Mario Gju May 30 '18 at 20:35
  • 1
    No, you only export a single object. Just add each function to the exported object. ex module.exports = {makeConnection, disconnect, dosomethingelse} – Deadron May 30 '18 at 22:12