Node.js with Postgres database connectivity
It is connecting to a PostgreSQL database using the pg module in Node.js. This version creates a database if it doesn’t exist and lists all available databases.
You need to install pg or mysql as per your database.
npm install pg
const { Client } = require('pg');
async function main() {
// Connection configuration
const config = {
host: "localhost",
user: "postgres", // Replace with your PostgreSQL username
password: "mypassword", // Replace with your PostgreSQL password
port: 5432, // Default PostgreSQL port
};
// Create a client to connect to the default "postgres" database
const client = new Client({ ...config, database: "postgres" });
try {
// Connect to PostgreSQL
await client.connect();
console.log("Connected to PostgreSQL!");
// Create database if it doesn't exist
const dbName = "mydb";
const createDbQuery = `SELECT 'CREATE DATABASE ${dbName}' WHERE NOT EXISTS (
SELECT FROM pg_database WHERE datname = '${dbName}'
);`;
const createDbResult = await client.query(createDbQuery);
if (createDbResult.rowCount > 0) {
console.log(`Database '${dbName}' created successfully.`);
} else {
console.log(`Database '${dbName}' already exists.`);
}
// List all databases
const listDbQuery = `SELECT datname FROM pg_database WHERE datistemplate = false;`;
const dbListResult = await client.query(listDbQuery);
console.log("Available databases:");
dbListResult.rows.forEach((db) => console.log(JSON.stringify(db)));
} catch (err) {
console.error("Error:", err.message);
} finally {
// Disconnect the client
await client.end();
console.log("Disconnected from PostgreSQL.");
}
}
// Run the main function
main();
Terminal Commands and logs
PS D:\React_Project\NodeProject> node NodeJsDBConnectivityExample.js
node:internal/modules/cjs/loader:1252
throw err;
^
Error: Cannot find module 'pg'
Require stack:
- D:\React_Project\NodeProject\NodeJsDBConnectivityExample.js
at Function._resolveFilename (node:internal/modules/cjs/loader:1249:15)
at Function._load (node:internal/modules/cjs/loader:1075:27)
at TracingChannel.traceSync (node:diagnostics_channel:315:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:218:24)
at Module.require (node:internal/modules/cjs/loader:1340:12)
at require (node:internal/modules/helpers:141:16)
at require (node:internal/modules/helpers:141:16)
at Object.<anonymous> (D:\React_Project\NodeProject\NodeJsDBConnectivityExample.js:1:20)
at Object.<anonymous> (D:\React_Project\NodeProject\NodeJsDBConnectivityExample.js:1:20)
at Module._compile (node:internal/modules/cjs/loader:1546:14)
at Module._compile (node:internal/modules/cjs/loader:1546:14)
at Object..js (node:internal/modules/cjs/loader:1689:10)
at Object..js (node:internal/modules/cjs/loader:1689:10)
at Module.load (node:internal/modules/cjs/loader:1318:32) {
at Module.load (node:internal/modules/cjs/loader:1318:32) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'D:\\React_Project\\NodeProject\\NodeJsDBConnectivityExample.js' ]
code: 'MODULE_NOT_FOUND',
requireStack: [ 'D:\\React_Project\\NodeProject\\NodeJsDBConnectivityExample.js' ]
}
Node.js v22.11.0
Node.js v22.11.0
PS D:\React_Project\NodeProject> npm install pg
PS D:\React_Project\NodeProject> npm install pg
added 13 packages, and audited 104 packages in 1s
15 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
PS D:\React_Project\NodeProject> node NodeJsDBConnectivityExample.js
Connected to PostgreSQL!
Database 'mydb' created successfully.
Available databases:
{"datname":"postgres"}
Disconnected from PostgreSQL.
PS D:\React_Project\NodeProject> node NodeJsDBConnectivityExample.js
Connected to PostgreSQL!
Database 'mydb' already exists.
Available databases:
{"datname":"postgres"}
{"datname":"mydb"}
Disconnected from PostgreSQL.
PS D:\React_Project\NodeProject>
Recent Comments