Returns from SELECT using node-postgres

Cannot get results from SELECT queries in node-postgres. Now the lines are omitted at the end of the code. This select simply returns the next value from the sequence in POSTGRESQL. I know that you cannot get results from the callback, but is there anyone here who used node-postgres (or any other database modules for node) that might know about the fix?

client.connect(); var query = client.query("SELECT nextval(\'idgenerator\');"); var rows = []; query.on('row', function(row, res) { rows.push(row); }); query.on('end', function(result) { console.log(result.rowCount + ' rows were received'); }); //client.end(); console.log(rows); 
+7
rest postgresql
source share
2 answers

You will need to learn javascript / nodejs and event programming.

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

It is asynchronous; therefore, query.on () logs the event and returns.

So when console.log(rows) is called, the rows are still empty, because the "row" event has not yet been triggered in the request.

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

Throughout the code, you also need to write console.log . You will see an asynchronous thing.

+5
source share

If we did not call the result.addRow () method, the array of strings would be empty in the final 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(); }); 

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

+4
source share

All Articles