I am just starting with postgresql.
I have successfully made connection with cloud database and retrieved data using nodejs ‘postgres’ package, but the program doesn’t end after it logs all the data on console, it’s still running. Why is that?
import postgres from 'postgres'
import "dotenv/config"
const sql = postgres({
host: process.env.DATABASE_HOST,
database: process.env.DATABASE_NAME,
username: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
ssl: 'require',
})
async function getInfo() {
const users = await sql`
select * from information_schema.tables
`
return users
}
getInfo().then((data) => console.log(data))
>Solution :
The node project will still run because of the database connection, you need to end it after retrieving the data.
async function getInfo() {
try {
const users = await sql`
select * from information_schema.tables
`;
return users;
} finally {
sql.end(); // Close the connection
}
}
Also, optionally you could force the node to shutdown with process.exit(0)
getInfo().then((data) => {
console.log(data);
process.exit(0);
});