Languages
[Edit]
EN

Node.js / PostgreSQL - list sizes of databases

3 points
Created by:
Lillie-Rose-Finnegan
489

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";

Β 

Alternative titles

  1. Node.js / PostgreSQL - check sizes of databases
  2. Node.js / PostgreSQL - print sizes of databases
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Node.js - PostgreSQL - Problems

Native Advertising
πŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

β€οΈπŸ’» πŸ™‚

Join