node-postgres

8.20.0 · active · verified Sat Apr 18

node-postgres (pg) is a non-blocking PostgreSQL client for Node.js, offering both a pure JavaScript implementation and optional native libpq bindings with a unified API. As of version 8.20.0, it provides essential features like connection pooling, extensible data-type coercion, and support for parameterized queries, named statements, async notifications, and bulk import/export.

Common errors

Warnings

Install

Imports

Quickstart

Connects to a PostgreSQL database using a connection pool, executes a simple `SELECT NOW()` query, logs the result, and properly releases the client and closes the pool.

import { Pool } from 'pg';

async function runQuery() {
  // Ensure your POSTGRES_URL environment variable is set,
  // e.g., 'postgresql://user:password@host:5432/database'
  const pool = new Pool({
    connectionString: process.env.POSTGRES_URL ?? 'postgresql://user:password@localhost:5432/testdb',
  });

  try {
    const client = await pool.connect();
    const res = await client.query('SELECT NOW() AS current_time');
    console.log('Current time from PostgreSQL:', res.rows[0].current_time);
    client.release(); // Release the client back to the pool
  } catch (err) {
    console.error('Database query failed', err);
  } finally {
    await pool.end(); // Close the pool when done with all operations
  }
}

runQuery();

view raw JSON →