2

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)
2
  • You close the connection to the database, before all rows are processed. remember, that pretty much all calls to the database are asynchronous. Commented Jul 14, 2015 at 10:06
  • oh.. so that's it! unbelieveable! Commented Jul 14, 2015 at 10:06

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.