Read and Output Postgresql Data Using Node.js
Set up the Node.js Application

Setting up a Node.js server to access data from a Postgresql database is simple.

Start with the basic Node.js setup. We’ll create an app called myDatabaseApp.

mkdir myDatabaseApp

cd myDatabaseApp

yarn init

Since this application will use Postgresql, we’ll need the appropriate node module.

yarn add pg

Create index.js. The code will connect to a database called node_test, and output records from the users table.

const pg = require('pg') const config = {

database: 'node_test'

} const pool = new pg.Pool(config); pool.connect((err, client, done) => {

if (err) throw err;

client.query('SELECT name, age FROM users', (err, res) => {

if (err)

console.log(err.stack);

else {

console.log(res.rows);

}

pool.end()

})

})

Set Up The Postgresql Database

We’ll need a Postgresql database and a little sample data. I used Postico to quickly set this up. Postico is a very useful Postgres client for database management. It can be downloaded and installed directly from the Postico website.

Once the client is downloaded, create a new database called node_test, add a new table called users, and then add a few columns: id, name, and age.
['Clark Johnson']
['Postgres', 'Postgresql', 'Nodejs']