Using node-postgres to Connect to bit.io

First, install node-postgres for your node project.

npm install pg

Then sign in to bit.io and click "Connect" to get your connection info.

Using that information, you can connect to bit.io and query your databases or public databases hosted on bit.io. Try copying the code below and swapping out the connection information.

const { Pool } = require('pg');

// Create a connection pool using the connection information provided on bit.io.
const pool = new Pool({
    user: 'GettingStarted',
    host: 'db.bit.io',
    database: 'dliden/2020_Census_Reapportionment', // public database 
    password: '<bitio_key>', // key from bit.io database page connect menu
    port: 5432,
    ssl: true,
});

pool.query('SELECT * FROM "dliden/2020_Census_Reapportionment"."Historical Apportionment" limit 10;', (err, res) => {
    console.table(res.rows); // you could also just console.log, but console.table is neat :)
});

Now run the program using node and you should see the rows you requested printed out in the console.

node main.js
17341734

🚧

Error: Connection terminated unexpectedly — Use a connection pool

It is recommended to use a node-postgres connection pool with bit.io (as shown in the connection snippet above). bit.io automatically closes idle connections (after 60 seconds, at the time of writing) and the connection pool interface will automatically handle opening new connections as needed.

To learn more about using your bit.io Postgres database with node.js, read the node-postgres docs.


What’s Next