Node.js - TypeError: Client is not a constructor

Viewed 3234

I am trying the following:

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

  console.log(Client);

  const client = new Client({
      user: 'Username censored',
      host: 'Host censored',
      database: 'gisuebung',
      password: 'Passworded censored',
      port: 5432,
  });
  
  client.connect();
  

When I run this however, I get the following Error: Error in v-on handler: "TypeError: Client is not a constructor"

I wrote this after a snippet I found online and it seems everywhere I look people did the exact same thing. Can anyone tell me what I am doing wrong?

2 Answers

This is a JS error:

Try this, it worked for me:
const { Client } = require('pg');
const Client = require('pg').Client;

-- ES module:
import pg from 'pg';
const Client = pg.Client;

Try this, it worked for me:

const { Client } = require('pg');
const client = new Client({
 user: "postgres",
 database: "databasename",
 port: 5432,
 host: "localhost",
 password: "yourpassword",
 ssl: false
});


client.connect();
client.query("select * from cad_client")
     .then(results => {
         const result = results.rows
         console.log(result)
     })
     .finally(() => client.end())
Related