Skip to content

How to do queries from a Node.js app?

Course: SQL databases - chapter 8

In the end, postgres exposes a protocol that someone needs to talk to be able to send these commands (update, delete) to the database.

psql is one such library that takes commands from your terminal and sends it over to the database.

To do the same in a Node.js , you can use one of many Postgres clients

https://www.npmjs.com/package/pg

Non-blocking PostgreSQL client for Node.js.

Documentation - https://node-postgres.com/

Connecting -

import { Client } from 'pg'
const client = new Client({
host: 'my.database-server.com',
port: 5334,
database: 'database-name',
user: 'database-user',
password: 'secretpassword!!',
})
client.connect()

Querying -

const result = await client.query('SELECT * FROM USERS;')
console.log(result)
// write a function to create a users table in your database.
import { Client } from 'pg'
const client = new Client({
connectionString: "postgresql://postgres:mysecretpassword@localhost/postgres"
})
async function createUsersTable() {
await client.connect()
const result = await client.query(`
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
`)
console.log(result)
}
createUsersTable();