Skip to content

PostgreSQL wire: Node.js (node-postgres)

# host
postgres.internal
warehouse.internal
# port
5432
5432 (PostgreSQL wire)
# user / password / database
PostgreSQL values
MachWarehouse values
Terminal window
npm install
DATABASE_URL=postgresql://app:...@warehouse.internal:5432/demo npm start

Library: pg 8.23.1.

The program as it is kept and tested in the Mach Database Warehouse repository; highlighted lines read the connection setting.

index.mjs
// Aggregate over the PostgreSQL wire with node-postgres. Plain pg code.
import pg from 'pg';
const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
const { rows } = await client.query(
'SELECT country, count(*) AS events, sum(revenue) AS revenue FROM events GROUP BY country ORDER BY revenue DESC',
);
for (const r of rows) console.log(`${r.country}\t${r.events}\t${r.revenue}`);
await client.end();
package.json
{
"name": "machwarehouse-example-postgres-node",
"private": true,
"type": "module",
"scripts": { "start": "node index.mjs" },
"dependencies": { "pg": "8.23.1" },
"engines": { "node": ">=20" }
}