Connect PostgreSQL with Node.js
Here we are using the most popular Node.js module ‘node-postgres’ for connecting the PostgreSQL database with Node.js.
Before discussing the ways to connect PostgreSQL with Node.js, considering Node.js and PostgreSQL are installed on your environment.
Install the PostgreSQL ( pg ) module using npm:
npm install pg
Let's see different ways to connect PostgreSQL with Node.js.
- Environment variables
- Programmatic
- Connection URI
Environment variables
When your Node.js process boots up it will automatically provide access to all existing environment variables by creating an env object as a property of the process global object.
console.log(process.env);
This code should output all environment variables that this Node.js process is aware of.
To access one specific variable, access it like any property of an object:
console.log(‘The value of path is:’, process.env.PORT);
Since process.env is simply a normal object we can set/override the values very easily:
process.env.MY_VARIABLE = ‘dummyname’;
This allows us to write our programs without having to specify connection information in the program and lets us reuse them to connect to different databases without having to modify the code.
db_connection.js
const { Client } = require(‘pg’);
const client = new Client()
client.query(‘SELECT NOW()’, (err, res) => {
console.log(err, res)
client.end()
})
The default values for the environment variables used are:
PGHOST=’localhost’
PGUSER=process.env.USER
PGDATABASE=process.env.DATABASE
PGPASSWORD=process.env.PASSWORD
PGPORT=5432
Programmatic
node-postgres also supports configuring a client programmatically with connection information.
const { Client } = require(‘pg’);
const client = new Client({
user: ‘dbuser’,
host: ‘database.server.com’,
database: ‘mydb’,
password: ‘secretpassword’,
port: 3211,
})client.connect()
client.query(‘SELECT NOW()’, (err, res) => {
console.log(err, res)
client.end()
})
Connection URI
We can initialize a client with a connection string URI as well.
const { Client } = require(‘pg’)
const connectionString = ‘postgresql://dbuser:secretpassword@database.server.com:3211/mydb’
const client = new Client({
connectionString: connectionString,client.connect
client.query(‘SELECT NOW()’, (err, res) => {
console.log(err, res)
client.end()
})
Please refer to pg for more details