Connecting to PostgreSQL using Node.js
Node.js applications can interact with PostgreSQL databases using the node‑postgres (pg) package. On ruachost.com, you can use this library to establish connections, run queries, and manage your data directly from your Node.js code.
Why Use Node.js for PostgreSQL?
Section titled “Why Use Node.js for PostgreSQL?”- Asynchronous I/O makes queries fast and scalable.
- Widely supported library (
pg) with robust features. - Perfect for modern web applications and APIs.
Steps to Connect to PostgreSQL Using Node.js
Section titled “Steps to Connect to PostgreSQL Using Node.js”Step 1: Install Node.js and pg
Section titled “Step 1: Install Node.js and pg”-
Log in to your hosting account via SSH.
-
Ensure Node.js is installed.
-
Install the
pgpackage:Terminal window npm install pg
Step 2: Write Connection Code
Section titled “Step 2: Write Connection Code”Example
Section titled “Example”// Import the pg moduleimport pg from 'pg';const { Client } = pg;
// Configure connectionconst client = new Client({ host: 'localhost', database: 'yourdbname', user: 'yourusername', password: 'yourpassword', port: 5432});
// Connect to PostgreSQLawait client.connect();
// Run a queryconst res = await client.query('SELECT fname, lname FROM employee');console.log(res.rows[0]);
// Close connectionawait client.end();Step 3: Handle Common Errors
Section titled “Step 3: Handle Common Errors”-
If you see:
SyntaxError: Cannot use import statement outside a module→ Create a
package.jsonfile in your project directory and add:{"type": "module"} -
This enables ES module syntax (
import) in Node.js..