CiscoKidx
CiscoKidx

Reputation: 920

require function and variable from another file = nodejs

I am trying to offload some of the bulk from my app and came across this issue.

Here is my code:

// foo.js:

var mysql = require('mysql');

module.exports = {
  home: function () {
    return mysql.createConnection({
      host : '2.2.2.2',
      user: 'admin',
      password: 'xxxxxx',
      database : 'mlb'
    });
  }

// bar.js:

var dbConnect = require('./foo.js');

dbConnect.home.query('SELECT * from batters;', function(err, res, body) {
  if (err) throw err;
  var string_data = JSON.stringify(res);
  var jsonData = JSON.parse(string_data);
  console.log(jsonData);
});

The error i receive is undefined is not a function... What am I doing wrong?

Upvotes: 0

Views: 525

Answers (2)

Kip
Kip

Reputation: 558

Wouldn't home need to be like this:
dbConnect.home().query

Upvotes: 3

CiscoKidx
CiscoKidx

Reputation: 920

I needed to instantiate the imported function before calling its method.

Correct code for bar.js is:

var dbConnect = require('./test.js');

var connection = dbConnect.home();

connection.query('SELECT * from batters;', function(err, res, body) {
  if (err) throw err;
  var string_data = JSON.stringify(res);
  var jsonData = JSON.parse(string_data);
  console.log(jsonData);
});

Upvotes: 0

Related Questions