Antonio Laguna
Antonio Laguna

Reputation: 9282

How to export properly in node.js?

I'm running some issues with my node application after upgrading to Express 3.0. So, since I'm rewriting it, I was trying to follow the style of routes/index.js because it looks clean.

So, in my main app.js I have some variables such as:

var calls = 0;
var agents = [];

And also use the node-mysql module. However, the routes definition doesn't have app.js scope but their own scope so calls and agents aren't visible.

How should I make them visible?

For mysql I tried something like:

// libraries/mysql.js
mysql = require('mysql');
var mysql_conf = {
    host: myhost,
    user: myuser,
    password: mypass,
    database: mydb
};
var mysql_client = mysql.createClient(mysql_conf);

exports.mysql_client;

//Later in routes/index.js
mysql_client = require('../helpers/mysql.js');

But it seems not to work as it says TypeError: Object #<Object> has no method 'query'

Any hints please?

Upvotes: 0

Views: 609

Answers (1)

Matt Ball
Matt Ball

Reputation: 359776

The line

exports.mysql_client;

Does not actually assign anything to the mysql_client property of exports. It accesses a property, and immediately discards the value. You need to do something like this:

var mysql_client = mysql.createClient(mysql_conf);
exports.mysql_client = mysql_client;

// or simply

exports.mysql_client = mysql.createClient(mysql_conf);

Upvotes: 2

Related Questions