Nodejs and PostgreSQL, Practical Introduction (Connection and Basic Queries with Javascript)
--
In this tutorial, I will show you how to create a Node Server and the basic queries with PostgreSQL.
Prerequisites
First thing first
To start it is necessary to first create a new folder called as you want, for this tutorial I am going to call it node-postgres, and then inside the folder open a new terminal with the folder path and initialize our project, for this, just write the following command in the terminal.
npm init -t
This will create a file called package.json with default values, for our project which contains all the project references such as the author, repository, version, and most important of all the project dependencies.
Before starting to write our code, we are going to install the dependencies, for this tutorial only “express” and “pg” are necessary. So we are going to write the following command in the console:
npm i express pg
And finally, for dev dependencies:
npm i -D nodemon
Now we are going to give our project a bit of structure, first, we are going to create a folder called “src” where we will place all our files.
Inside the src folder, we are going to create a file called index.js, this file will be the initial configuration of our server so we are going to add the following lines of code.
const express = require('express')const app = express()app.use(express.json())app.use(express.urlencoded({extended:false}))const PORT = 3000app.listen(PORT);console.log(`Running on port ${PORT}`)