Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-postgres, Connection terminated unexpectedly

I'm trying to connect to a remote database using node-postgres.

I can connect using the psql client, but I get the error Connection terminated unexpectedly while trying to run this (with same connection string as in psql client):

const { Pool, Client } = require('pg')
const connectionString = '...'

const pool = new Pool({
  connectionString: connectionString,
})

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

const client = new Client({
  connectionString: connectionString,
})
client.connect()

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

I've also been trying to connect with Sequelize ORM, but got the same error.

@EDIT

Using native mode fixed problem for client query using pg, and sequelize

const { Pool, Client } = require('pg').native

like image 217
John Jeromin Avatar asked Apr 06 '18 16:04

John Jeromin


2 Answers

I started having the same problem, but only with long time queries, i found a possible solution by setting idleTimeoutMillis in the Pool constructor, for example to 20000 (the default value is 10000)

See https://node-postgres.com/api/pool#new-pool-config-object-

like image 85
Arturo Torres Vázquez Avatar answered Sep 30 '22 06:09

Arturo Torres Vázquez


Working with processes that could take hours, I found the solution using Pool but setting idleTimeoutMillis and connectionTimeoutMillis both with 0. Example:

const { Pool } = require('pg')

const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'my_database',
  password: 'XXXX',
  port: 5423,
  idleTimeoutMillis: 0,
  connectionTimeoutMillis: 0,
});
like image 42
Emeeus Avatar answered Sep 30 '22 06:09

Emeeus