MikeH
MikeH

Reputation: 43

Node.js - TypeError: Client is not a constructor

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?

Upvotes: 3

Views: 14652

Answers (3)

rawa08
rawa08

Reputation: 135

This is a JS error:

Try this, it worked for me:

const { Client } = require('pg'); 
// or
const Client = require('pg').Client;

-- ES module:

import pg from 'pg';
const Client = pg.Client;

Upvotes: 12

Sandre
Sandre

Reputation: 756

Your code fine for CommonJS. But for ESM this error will raise.

Correct way to run in ESM:

import pg from 'pg'

const client = new pg.Client(config.dbConfig)

Upvotes: 1

Leandro Laurindo
Leandro Laurindo

Reputation: 1

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())

Upvotes: -1

Related Questions