node.js - How do I use node-postgres in a server? -


i'm writing node.js web server uses postgres database. used connect on each new request this:

app.get('/', function (req, res) {   pg.connect(pgconnstring, function (err, client) {     // ...   }); }); 

but after few requests, noticed 'out of memory' errors on heroku when trying connect. database has 10 rows, don't see how happening. of database access of form:

client.query('select * table', function (err, result) {   if (err) {     res.send(500, 'database error');     return;   }    res.set('content-type', 'application/json');   res.send(json.stringify({ data: result.rows.map(makejson) })); }); 

assuming memory error due having several persistent connections database, switched style saw in several node-postgres examples of connecting once @ top of file:

var client = new pg.client(pgconnstring); client.connect();  app.get('/', function (req, res) {   // ... }); 

but requests hang (indefinitely?) when try execute query after connection disrupted. (i simulated killing postgres server , bringing up.)

so how do 1 of these?

  1. properly pool postgres connections can 'reconnect' every time without running out of memory.
  2. have global client automatically reconnect after network failure.

i'm assuming you're using latest version of node-postgres, in connection pooling has been improved. must check connection pool, or you'll bleed connections:

app.get('/', function (req, res) {   pg.connect(pgconnstring, function (err, client, done) {     // stuff     done();   }); }); 

as error handling on global connection (#2, i'd use pool):

client.on('error', function(e){   client.connect(); // check error, etc in production app }); 

the "missing" docs on github wiki.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -