Reputation: 1476
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)
Upvotes: 1
Views: 4580
Reputation: 3783
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.
Upvotes: 2
Reputation: 74036
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.
Upvotes: 2