o9s
is a microblog
home archives search feed blogroll


Connect To Postgres With Node

Quick Prerequisites

  1. Install Postgres.
  2. Install Postbird. It’s a GUI for Postgres.
  3. Start Postgres and create a database.
  4. Start Postbird and add/remove tables, columns, etc.

Now The Node Stuff

I’m using the dotenv package to load environment variables from an .env file. You should add .env to your .gitignore. This keeps the secret database information out of your source control.

cd your_project_directory
npm install dotenv --save
vim .env

Copy the lines below in your .env file and change the values. The default username for a Postgres is postgres. There is not default password. The default port is 5432.

PGUSER=postgres
PGHOST=localhost
PGPASSWORD=
PGDATABASE=your_database_name
PGPORT=5432

The line below should be the first line of your index.js file.

require('dotenv').config();

You can now connect to your database like this.

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

client.connect();
client.query('SELECT 1+1')
  .then(result => console.log(result))
  .catch(err => console.log(err))
  .then(() => client.end);
Posted on 2018-02-14   #database     #postgres     #javascript     #node  






← Next post    ·    Previous post →