I am a newbie with Node and I am trying to learn how to make my modules work. Here is my express app:
var express = require('express');
var app = express();
var client = require('./config/postgres.js');
app.get('/users', function(req, res) {
var query = client.query('SELECT * FROM users');
query.on('row', function(row, result) {
result.addRow(row);
});
query.on('end', function(result) {
res.json(result);
});
});
And here is my module that I am trying to require
var pg = require('pg').native;
var connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/isx';
var client = new pg.Client(connectionString);
client.connect();
module.exports.client = client;
but in my main app, my client has no method 'query'
. If I just inline the code that is in the module
and I am require
ing in, then everything works fine. What is the difference between the 2 ways to access the code?
var client = require('./config/postgres.js');
...sets client equal to the export
object in your import. Since the export object has a single client
property with the query
function,
client.client.query()
is what you're looking for.
If you want to export just the client, use;
module.exports = client;