node-pg for integrating postgres with Node.js

node-pg or node-postgres is a collection of modules for integrating PostgreSQL with your Node.js application. There are other clients and ORMs like sequelize available to interface your applications with PostgreSQL. In this blog we will see how to do this with node-postgres. We already know that PostgreSQL is a database that runs on multiple platforms. The features of node-postgres are the following:

  • It uses a pure JavaScript client and native libpq bindings share the same API.

  • It supports callbacks, promises, async/await notifications with LISTEN/NOTIFY, connection pooling, prepared statements, cursors.

  • It also supports streaming results,C/C++ bindings etc.

Install node-pg using npm.


$ npm install pg


Let’s get started. Here is an example of how to connect,query and disconnect with async/await.


const { Client } = require('pg')

const client = new Client()

;(async () => {

  await client.connect()

  const res = await client.query('SELECT $1::text as message', ['Hello world!'])

  console.log(res.rows[0].message) // Hello world!

  await client.end()

})()


Another example for connecting, querying, and disconnecting using callback.


const { Client } = require('pg')

const client = new Client()

client.connect()

client.query('SELECT $1::text as message', ['Hello world!'], (err, res) => {

  console.log(err ? err.stack : res.rows[0].message) // Hello World!

  client.end()

})