Welcome to our comprehensive guide on using Node.js with PostgreSQL! In this tutorial, we'll walk you through the process of setting up a Node.js application that interacts with a PostgreSQL database. By the end of this lesson, you'll have a solid understanding of how to use these powerful tools together.
Let's start by understanding what Node.js and PostgreSQL are.
Node.js is an open-source, cross-platform JavaScript runtime environment that enables you to run JavaScript on the server-side and build scalable and high-performance applications.
PostgreSQL is a powerful, open-source object-relational database management system (ORDBMS) that uses and extends the SQL language. It is highly scalable and can handle large amounts of data with ease.
To get started, you'll need to have Node.js and PostgreSQL installed on your system.
npm init
Follow the prompts to set up your project.
pg PackageThe pg package is a Node.js client for PostgreSQL. To install it, run the following command in your project directory:
npm install pg
Now let's create a new JavaScript file called db.js in your project directory. In this file, we'll write the code to connect to our PostgreSQL database.
// db.js
const { Client } = require('pg');
const client = new Client({
user: 'your_database_user',
host: 'localhost',
database: 'your_database_name',
password: 'your_database_password',
port: 5432,
});
client.connect();
module.exports = client;Replace 'your_database_user', 'your_database_name', and 'your_database_password' with your PostgreSQL database credentials.
Now let's create a simple example where we insert data into the database and fetch it back.
Create a new JavaScript file called app.js in your project directory.
// app.js
const client = require('./db');
client.query('CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name TEXT, email TEXT);', (err, res) => {
if (err) throw err;
console.log('Table created...');
});
const insertUser = (name, email) => {
const query = 'INSERT INTO users (name, email) VALUES ($1, $2);';
const values = [name, email];
client.query(query, values, (err, res) => {
if (err) throw err;
console.log('User added...');
});
};
const fetchUsers = () => {
const query = 'SELECT * FROM users;';
client.query(query, (err, res) => {
if (err) throw err;
console.log('Users:');
res.rows.forEach(row => {
console.log(row);
});
});
};
insertUser('John Doe', 'john.doe@example.com');
fetchUsers();
client.end();This example creates a table called users if it doesn't exist, inserts a new user, and fetches all users from the database.
To run the application, simply run the following command in your project directory:
node app.js
insertUser function call with your own data when testing the application.Congratulations! You've now learned how to use Node.js with PostgreSQL. You can now create powerful, data-driven applications using these powerful tools.
What is Node.js used for?
Now that you have a solid understanding of how to use Node.js with PostgreSQL, you can dive deeper into more complex examples and explore various Node.js libraries for working with PostgreSQL. Happy coding! 🎯