The code crashes at the query object creation.
var conString = "postgres://mydbusr:thepassword@localhost/mydb";
var client = new pg.Client(conString);
client.connect(function(err) {
if (err) {
return console.error('could not connect to postgres', err);
}
var query = client.query('SELECT id FROM people'); //THE PROBLEM IS HERE
query.on('row', function(row) {
//Do something
});
client.end();
});
And this is the errror that I really don't understand:
events.js:72
throw er; // Unhandled 'error' event
^
Error: Connection terminated
at null.<anonymous> (/liveupdates/node_modules/pg/lib/client.js:184:29)
at g (events.js:180:16)
at EventEmitter.emit (events.js:92:17)
at Socket.<anonymous> (/liveupdates/node_modules/pg/lib/connection.js:66:10)
at Socket.EventEmitter.emit (events.js:95:17)
at TCP.close (net.js:466:12)
-
You close the connection to the database, before all rows are processed. remember, that pretty much all calls to the database are asynchronous.Sirko– Sirko2015年07月14日 10:06:42 +00:00Commented Jul 14, 2015 at 10:06
-
oh.. so that's it! unbelieveable!user568021– user5680212015年07月14日 10:06:59 +00:00Commented Jul 14, 2015 at 10:06
2 Answers 2
You forgot, that pretty much all calls to the database are asynchronous.
In your code you closed the connection using
client.end();
without waiting, that all queries and the respective responses have been processed.
I agree with Sirko, put that client.end()
inside query.on()
with a condition which satisfies that all your rows have been fetched from database.
Moreover, remove the return statement in the block where you're handling the error. Generally most db clients tries multiple times to connect the database when encountered with errors. If you return on encountering the error first time, your client won't try even the second time.