Returning result from SELECT with node-postgres Returning result from SELECT with node-postgres postgresql postgresql

Returning result from SELECT with node-postgres


You'll have to learn javascript / nodejs, and event programming.

query.on('row', function() { /*CODE*/ }) means : "when a row is read, execute CODE".

This is asynchronous; so query.on() register the event, and returns.

So when console.log(rows) is called, rows is still empty, because no 'row' event has been triggered on query, yet.

You should try putting 'console.log(rows)' in the body of the query.on('end') event handler.

Everywhere in the code, also, you should write some console.log. You'll see the asynchronous thing.


If we did not call the result.addRow() method, the rows array would be empty in the end event.

var query = client.query("SELECT firstname, lastname FROM emps ORDER BY lastname, firstname");query.on("row", function (row, result) {    result.addRow(row);});query.on("end", function (result) {    console.log(JSON.stringify(result.rows, null, "    "));    client.end();});

Ref: http://nodeexamples.com/2012/09/21/connecting-to-a-postgresql-database-from-node-js-using-the-pg-module/