Skip to content Skip to sidebar Skip to footer

Node Js And Pg Module 'how Can I Really Close Connection?'

I'm going crazy with node pg module, getting 'too many clients already' error. My app.js file for example, manages some routes in which I query some data to postgres. app.js looks

Solution 1:

The recommended pattern is to use client pooling. From the node-postgres documentation:

Generally you will access the PostgreSQL server through a pool of clients. A client takes a non-trivial amount of time to establish a new connection. A client also consumes a non-trivial amount of resources on the PostgreSQL server - not something you want to do on every http request. Good news: node-postgres ships with built in client pooling.

var pg = require('pg');
var conString = "postgres://username:password@localhost/database";

//this initializes a connection pool//it will keep idle connections open for a (configurable) 30 seconds//and set a limit of 20 (also configurable)
pg.connect(conString, function(err, client, done) {
  if(err) {
    returnconsole.error('error fetching client from pool', err);
  }
  client.query('SELECT $1::int AS number', ['1'], function(err, result) {
    //call `done()` to release the client back to the pooldone();

    if(err) {
      returnconsole.error('error running query', err);
    }
    console.log(result.rows[0].number);
    //output: 1
  });
});

Don't forget to call done() or you'll be in trouble!

Post a Comment for "Node Js And Pg Module 'how Can I Really Close Connection?'"