Node.js / Express - How to get variables defined in app.js in routes/index.js?

André picture André · Dec 30, 2013 · Viewed 9.2k times · Source

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

Answer

robertklep picture robertklep · Dec 30, 2013

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;
  ...
};