Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I use node-postgres in a server?
    primarykey
    data
    text
    <p>I'm writing a Node.js web server that uses a Postgres database. I used to connect on each new request like this:</p> <pre><code>app.get('/', function (req, res) { pg.connect(pgconnstring, function (err, client) { // ... }); }); </code></pre> <p>But after a few requests, I noticed 'out of memory' errors on Heroku when trying to connect. My database has only 10 rows, so I don't see how this could be happening. All of my database access is of this form:</p> <pre><code>client.query('SELECT * FROM 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) })); }); </code></pre> <p>Assuming that the memory error was due to having several persistent connections to the database, I switched to a style I saw in several <code>node-postgres</code> examples of connecting only once at the top of the file:</p> <pre><code>var client = new pg.Client(pgconnstring); client.connect(); app.get('/', function (req, res) { // ... }); </code></pre> <p>But now my requests hang (indefinitely?) when I try to execute a query after the connection is disrupted. (I simulated it by killing a Postgres server and bringing it back up.)</p> <p>So how do I do one of these?</p> <ol> <li>Properly pool Postgres connections so that I can 'reconnect' every time without running out of memory.</li> <li>Have the global client automatically reconnect after a network failure.</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload