6

I'm new to Node.js and Express.

How can I access the variable created in "app.js" called "pg" in "routes/index.js"?

app.js

/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var pg = require('pg');
var conString = "postgres://someuser:somepass@localhost/postgres"

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

routes/index.js

/*
 * GET home page.
 */

exports.index = function(req, res){

    var client = new pg.Client(conString);
    client.connect(function(err) {
      if(err) {
        return console.error('could not connect to postgres', err);
      }
      client.query('SELECT NOW() AS "theTime"', function(err, result) {
        if(err) {
          return console.error('error running query', err);
        }
        console.log(result.rows[0].theTime);
        //output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
        client.end();
      });
    });

I got the error in the browser:

Express 500 ReferenceError: pg is not defined

Can you guys give me a clue?

Best Regards

André
  • 24,706
  • 43
  • 121
  • 178
  • 4
    You'll probably want to just re-require pg in the files you wish to use it in. Node has module caching that means you'd have to go out of your way to force it to actually reprocess the file, so it's not costly to `require('pg')` again in a different file. – Lawrence Jones Dec 30 '13 at 15:35

3 Answers3

8

A simple way of passing anything to route handlers (whether they are declared in different files or not) in Express is to use app.locals:

// app.js
...
var app = express();
...
app.locals.someVar = someValue;
...

// somewhere else
module.exports.myhandler = function(req, res) {
  var someVar = req.app.locals.someVar;
  ...
};
robertklep
  • 198,204
  • 35
  • 394
  • 381
3
// app.js
var routes = require('./routes/index')({ varname: thevar });
...
...

And

// /routes/index.js
module.exports = function(options) {
    var moduleVar = options.varname;

    return {
        someMethod: function (req, res) { var i = moduleVar + 2; // etc},
        anotherMethod: function (req, res) {}
    };
};

I do this when I create a connection (or connection pool) and simply want my modules to have access to the db without having to create another connection. All depends on your project of course, one of my hit tracking modules uses it's own connection, so I pass it the db info and from there it does it's own thing. This allows me to have multiple apps using this tracker module while each connecting to their own db.

Chris
  • 1,611
  • 12
  • 11
  • 1
    When I do this "var routes = require('./routes')({ pg: pg, conString: conString});" I got the error, TypeError: object is not a function – André Dec 30 '13 at 15:53
  • Did you modify your routes module? If it's not wrapped up in the exports = function(options), it won't work. – Chris Dec 30 '13 at 15:59
0

You could define the variable without the var keyword to make the variable global.

Nisthar
  • 89
  • 3
  • 13