How to make connection to Postgres via Node.js?

Sometimes, we want to make connection to Postgres via Node.js.

In this article, we’ll look at how to make connection to Postgres via Node.js.

How to make connection to Postgres via Node.js?

To make connection to Postgres via Node.js, we can use the pg module.

To install it, we run

npm i pg

Then we use it by writing

const {
  Pool
} = require('pg');

const config = {
  user: 'foo',
  database: 'my_db',
  password: 'secret',
  host: 'localhost',
  port: 5432,
  max: 10,
  idleTimeoutMillis: 30000
};

const pool = new Pool(config);
pool.on('error', (err, client) => {
  console.error('idle client error', err.message, err.stack);
});
pool.query('SELECT $1::int AS number', ['2'], (err, res) => {
  if (err) {
    return console.error('error running query', err);
  }
  console.log('number:', res.rows[0].number);
});

to create a new Pool instance with the config object that has the database host, name, port, and credentials.

Then we call pool.on with 'error' to catch any errors with the connection.

And then we call pool.query to make a database query with the parameterized SQL string, values, and a callback that has the result of the query.

Conclusion

To make connection to Postgres via Node.js, we can use the pg module.