Kaizer Sozay Kaizer Sozay - 3 years ago 99
Node.js Question

What is a simple command I can run to test if I can connect to PostgreSQL using node-postgres?

My file db/index.js

const { Pool } = require('pg');
const pool = new Pool;

module.exports = {
query: (text, params, callback) => {
return pool.query(text,params,callback);
}
};


In my main file main.js I do:

const db = require('./db/index');


What command can I run on db to figure out if node-postgres is able to connect to my Postgres setup correctly?

Answer Source

To simply test if you can connect from node.js to pgsql database you can use the following snippet:

const { Pool } = require('pg')
const pool = new Pool()

pool.query('SELECT NOW()', (err, res) => {
  console.log(err, res)
  pool.end()
})

// or you can use async/await instead of callbacks
const res = await pool.query('SELECT NOW()')
console.log(res)
await pool.end()

This should return the response in form of pg.Result object containing current datetime.

node-postgres uses the same environment variables as libpq to connect to a PostgreSQL server, so to run the above code you can invoke it like so:

PGUSER=postgres PGHOST=127.0.0.1 PGPASSWORD=mysecretpassword PGDATABASE=postgres PGPORT=5432 node script.js

But you have to provide connection details to you database instance.

The default values for the environment variables used are:

PGHOST='localhost'
PGUSER=process.env.USER
PGDATABASE=process.env.USER
PGPASSWORD=null
PGPORT=5432

You can also provide the connection details programmatically, directly to either the Pool or Client instances. You can also use the connection string URI.

You can read more in the node-postgres documentation in the "connecting" section.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download