Categories
JavaScript Answers

How to make connection to Postgres via Node.js?

Spread the love

To make connection to Postgres via Node.js, we use the Pool constructor.

For instance, we write

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 call Pool with the connection config.

Then we call query to make a database query.

We get the results from the res parameter in the callback.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *