Connect with NodeJS Early availability
Connect to an Aiven for AlloyDB Omni database from NodeJS, using the pg
package.
Prerequisites
-
Aiven for AlloyDB Omni service running
-
npm
pg
package, which you can get by running:npm install pg --save
-
CA certificate (a file named
ca.pem
) downloaded from the service's Overview page
Connect to a service
-
Create a file named
index.js
with the following content:const fs = require("fs");
const pg = require("pg");
const config = {
user: "USER",
password: "PASSWORD",
host: "HOST",
port: "PORT",
database: "DATABASE",
ssl: {
rejectUnauthorized: true,
ca: fs.readFileSync("./ca.pem").toString(),
},
};
const client = new pg.Client(config);
client.connect(function (err) {
if (err) throw err;
client.query("SELECT VERSION()", [], function (err, result) {
if (err) throw err;
console.log(result.rows[0]);
client.end(function (err) {
if (err) throw err;
});
});
});Replace the connection parameters with the values available on the Overview page in the Aiven Console:
Variable Description USER
Aiven for AlloyDB Omni service username PASSWORD
Aiven for AlloyDB Omni service password HOST
Hostname for Aiven for AlloyDB Omni service connection PORT
Port for Aiven for AlloyDB Omni service connection DATABASE
Database name for Aiven for AlloyDB Omni service connection This code opens a connection to the database, runs a query checking the database version, and prints the response.
-
Run the code:
node index.js
Expect output like:
PostgreSQL 15.5 on x86_64-pc-linux-gnu, compiled by [...]