Connect Nodejs to PostGres SQL

Keith Dsouza
Mar 22, 2023

--

To connect to a PostgreSQL database using Node.js, you can use the pg module, which is a PostgreSQL client for Node.js.

Here’s an example code snippet to connect to a PostgreSQL database using Node.js:

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

const client = new Client({
user: 'your_database_user',
host: 'your_database_host',
database: 'your_database_name',
password: 'your_database_password',
port: your_database_port,
});

client.connect();

// Example query
client.query('SELECT NOW()', (err, res) => {
console.log(err ? err.stack : res.rows[0].now);
client.end();
});

In this example, you create a new Client object and pass in the database credentials, then call the connect() method to connect to the database. You can then use the query() method to execute SQL queries on the database.

You can find more information and examples on how to use the pg module in the official documentation: https://node-postgres.com/

--

--