Outputting rows from the pg module in Node / Postgres

In my Node app, I want to connect to a postgresql database to do some work on the entities. But I am having trouble getting it to work with Node. I have successfully connected and queried the database from a Python script with psycopg2, so I know that the connection part can work.

var DB_URL = "postgres://admin@localhost/mydb_development"
var db = new pg.Client(DB_URL);
db.connect();

.... more stuff here ....    


app.get('/test', function(request, response) {
  response.setHeader('Content-Type', 'text/plain');
  response.write("First!\n");
  var i = 0;
  var query = db.query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'", []);
  query.on('row', function(row) {
    console.log(row['table_name']);
    i++;
    response.write(String(row['table_name']) + "\n");
  });
  response.write("\nHello db; variable i=" + i + "!");
  response.end();
});

I am finding that the console.log(row['table_name']) is successfully outputting the table names to the console. However, it looks like neither the response variable nor i are available inside the closure... then how the heck am I supposed to get the results of the query to do stuff with it?!

response variable is available but not writeable, as you already ended it. i should also be available, but at the time you're writing it to the response, it has not been increased yet.

You probably wanted to end it (and to write the final line) after you've got all the rows. It could be achieved like this:

var DB_URL = "postgres://admin@localhost/mydb_development"
var db = new pg.Client(DB_URL);
db.connect();

.... more stuff here ....    


app.get('/test', function(request, response) {
  response.setHeader('Content-Type', 'text/plain');
  response.write("First!\n");
  var i = 0;
  var query = db.query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'", []);
  query.on('row', function(row) {
    console.log(row['table_name']);
    i++;
    response.write(String(row['table_name']) + "\n");
  });
  query.on('end', function () {
      response.write("\nHello db; variable i=" + i + "!");
      response.end();
  });
});