node-postgres
PostgreSQL client for node.js.
node-postgres (pg) is the standard Node.js library for connecting to a PostgreSQL database, supporting parameterized queries, connection pooling, async notifications, and large data streaming.
node-postgres (published on npm as the package "pg") is the standard library Node.js developers use to talk to a PostgreSQL database. PostgreSQL is an open-source relational database, the kind where you store data in tables and query it with SQL. node-postgres handles the connection between your JavaScript code and that database.
The library supports the full range of things you would typically need: running queries with parameters (so that user input is passed safely without SQL injection risk), connection pooling (reusing a shared set of database connections instead of opening a new one for every request, which is much more efficient in a server environment), and PostgreSQL-specific features like async notifications via LISTEN/NOTIFY and bulk data transfers via COPY.
Installing it is a single npm command. The library is written in plain JavaScript, so no additional system dependencies are required for basic use. There is an optional companion package (pg-native) that uses a lower-level C library called libpq instead, which can be faster in certain situations but requires that library to be installed on the machine.
The repository also contains several smaller related packages in the same codebase: a pool manager, a cursor for reading large result sets row by row, a streaming query interface, a connection string parser, and an implementation of the PostgreSQL wire protocol. Each is published to npm separately but developed together here.
The project is MIT licensed and maintained on GitHub through community contributions. A detailed documentation site is available at node-postgres.com.
Where it fits
- Connect a Node.js API server to PostgreSQL with a connection pool for efficient, reusable database access
- Run parameterized SQL queries safely, preventing SQL injection from user-supplied input
- Listen for real-time database events using PostgreSQL LISTEN/NOTIFY without polling
- Stream large query result sets row-by-row with pg-cursor to avoid loading everything into memory at once