EN
Node.js / PostgreSQL - list sizes of databases
3
points
In this article, we would like to show you how to listΒ the sizes of PostgreSQLΒ databasesΒ usingΒ Node.js.
Quick solution:
const { Client } = require('pg');
const client = new Client({
host: '127.0.0.1',
user: 'postgres',
password: 'password',
port: 5432,
});
const printDatabasesSizes = async () => {
const query = `
SELECT
"d"."datname" AS "database_name",
pg_size_pretty(pg_database_size("d"."datname")) AS "database_size"
FROM "pg_database" AS "d"
`;
try {
await client.connect(); // creates connection
const { rows } = await client.query(query); // sends query
console.table(rows);
} catch (error) {
console.error(error.stack);
return false;
} finally {
await client.end(); // closes connection
}
};
printDatabasesSizes();
Example result:Β
βββββββββββ¬ββββββββββββββββββ¬ββββββββββββββββ
β (index) β database_name β database_size β
βββββββββββΌββββββββββββββββββΌββββββββββββββββ€
β 0 β 'postgres' β '7965 kB' β
β 1 β 'dirask' β '8245 kB' β
β 2 β 'template1' β '7753 kB' β
β 3 β 'template0' β '7753 kB' β
β 4 β 'postgres_test' β '7753 kB' β
β 5 β 'my_database' β '7753 kB' β
β 6 β 'm_database' β '7753 kB' β
β 7 β 'database3' β '7753 kB' β
β 8 β 'my_datadbase' β '7753 kB' β
βββββββββββ΄ββββββββββββββββββ΄ββββββββββββββββ
Β
Native SQL query (used in the above example):
SELECT
"d"."datname" AS "database_name",
pg_size_pretty(pg_database_size("d".datname)) AS "database_size"
FROM "pg_database" AS "d";
Β