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
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-
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,
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With