
In this walkthrough, I am on a Linux system. Let's create a directory.
mkdir /tmp/nodejs_postgres
And move into the directory.
cd /tmp/nodejs_postgres
This issues you have the npm (Node.js Package Manager) CLI installed on your system. If not, check out my article FreeKB - Node.js - Install Node.js on Linux. Let's use the npm install command to install the postgres package.
npm install postgres
This will create the package.json file. Your package.json file should contain something like this.
{
"dependencies": {
"postgres": "^3.4.4"
}
}
Let's create a file named app.js.
touch app.js
And let's add the following to app.js. Notice this requires postgres.
const postgres = require('postgres');
const sql = postgres({
host: '10.11.12.13',
port:'5432',
database: 'mydb',
username: 'john.doe',
password: 'itsasecret'
})
async function query() {
return await sql `select * from my_table`
}
query()
.then(response => {
console.log(response)
process.exit(0)
})
.catch(err => {
console.error(err)
process.exit(1)
})
Be aware that if your are using a Node.js module instead of CommonJS, you will have "type": "module" in package.json.
{
"type": "module",
"dependencies": {
"postgres": "^3.4.4"
}
}
In this scenario, you will use import instead of require.
import postgres from "postgres";
Let's use the node CLI to run app.js and if all goes according the plan something like this should be returned.
~]$ node app.js
Result(4866) [
{
id: 175,
date_created: 2023-04-10T01:50:00.000Z,
date_updated: 2023-04-10T01:50:00.000Z,
email: 'john.doe@example.com',
phone: '123-456-7890',
firstname: 'John',
lastname: 'Doe'
},
{
id: 3385,
date_created: 2023-04-10T01:50:00.000Z,
date_updated: 2023-04-10T01:50:00.000Z,
email: 'jane.doe@example.com',
phone: '123-456-7890',
firstname: 'Jane',
lastname: 'Doe'
},
... 4766 more items
]
You probably want to loop through the results.
import postgres from "postgres"
const sql = postgres({
host: '10.11.12.13',
port:'5432',
database: 'mydb',
username: 'john.doe',
password: 'itsasecret'
})
async function query() {
return await sql `select id from my_table`
}
query()
.then(response => {
for ( let i = 0; i < response.length; i++ ) {
console.log(`id = ${response[i].id}`)
console.log(`firstname = ${response[i].firstname}`)
console.log(`lastname = ${response[i].lastname}`)
}
process.exit(0)
})
.catch(err => {
console.error(err)
process.exit(1)
})
Did you find this article helpful?
If so, consider buying me a coffee over at