Node Js Tutorials For Beginners

Posted on  by admin

Learning any new technology is a time-consuming process where it's easy to get lost. This is why we created this series of practical, bite-sized videos about Node.js for beginners so you can get up to speed quickly!

We choose to focus on the most important tasks and scenarios to make the most of your..

Learning any new technology is a time-consuming process where it's easy to get lost.

  • This is why we created this series of practical, bite-sized videos about Node.js for beginners so you can get up to speed quickly!
  • We choose to focus on the most important tasks and scenarios to make the most of your time.
  • While we won't cover every single thing to know about Node.js, you'll get all the essential knowledge you need to get started on your project.
  • To complete your learning journey, we also have an interactive course on Microsoft Learn: https://aka.ms/LearnNode.js.
  • Node.js Tutorial. Node.js Useful Resources.
  • Selected Reading. Node.js is a very powerful JavaScript-based platform built on Google Chrome's JavaScript V8 Engine.
  • It is used to develop I/O intensive web applications like video streaming sites, single-page applications, and other web applications.

Node.js is open source, completely free, and used by thousands of developers around the world. This tutorial is designed for software programmers who want to learn the basics of Node.js and its architectural concepts.

When to Use Node.js

This tutorial will give you enough understanding on all the necessary components of Node.js with suitable examples. Before proceeding with this tutorial, you should have a basic understanding of JavaScript.

As we are going to develop web-based applications using Node.js, it will be good if you have some understanding of other web technologies such as HTML, CSS, AJAX, etc.

Who uses Node.js

44 Lectures 7.5 hours . Eduonix Learning Solutions. 88 Lectures 17 hours . Eduonix Learning Solutions. 32 Lectures 1.5 hours . 8 Lectures 33 mins. 9 Lectures 2.5 hours .

SHIVPRASAD KOIRALA. 97 Lectures 6 hours . The modern web application has really come a long way over the years with the introduction of many popular frameworks such as bootstrap, Angular JS, etc.

All of these frameworks are based on the popular JavaScript framework.

Introduction to Node.js

But when it came to developing server-based applications, there was a kind of void, and this is where Node.js came into the picture. Node.js is also based on the JavaScript framework, but it is used for developing server-based applications.

While going through the entire tutorial, we will look into Node.js in detail and how we can use it to develop server-based applications.

What is Node.js?

Node.js is an open-source, cross-platform runtime environment used for the development of server-side web applications. Node.js applications are written in JavaScript and can be run on a wide variety of operating systems. Node.js is based on an event-driven architecture and a non-blocking Input/Output API that is designed to optimize an application’s throughput and scalability for real-time web applications.

Over a long period of time, the framework available for web development were all based on a stateless model.

A stateless model is where the data generated in one session (such as information about user settings and events that occurred) is not maintained for usage in the next session with that user.

  • A lot of work had to be done to maintain the session information between requests for a user.
  • But with Node.js, there is finally a way for web applications to have real-time two-way connections, where both the client and server can initiate communication, allowing them to exchange data freely.
  • We will have a look into the real worth of Node.js in the coming chapters, but what is it that makes this framework so famous.
  • Over the years, most of the applications were based on a stateless request-response framework.
  • In these sort of applications, it is up to the developer to ensure the right code was put in place to ensure the state of web session was maintained while the user was working with the system.
  • But with Node.js web applications, you can now work in real-time and have a 2-way communication.
  • The state is maintained, and either the client or server can start the communication.

Let’s look at some of the key features of Node.js. Asynchronous event-driven IO helps concurrent request handling – This is probably the most significant selling point of Node.js.

This feature basically means that if a request is received by Node for some Input/Output operation, it will execute the operation in the background and continue with processing other requests.This is quite different from other programming languages.

A simple example of this is given in the code below. The above code snippet looks at reading a file called Sample.txt.

In other programming languages, the next line of processing would only happen once the entire file is read.

But in the case of Node.js the important fraction of code to notice is the declaration of the function (‘function(error,data)’).

This is known as a callback function. So what happens here is that the file reading operation will start in the background. And other processing can happen simultaneously while the file is being read.

Once the file read operation is completed, this anonymous function will be called, and the text “Reading Data completed” will be written to the console log.

Node uses the V8 JavaScript Runtime engine, the one which is used by Google Chrome. Node has a wrapper over the JavaScript engine which makes the runtime engine much faster and hence the processing of requests within Node also become faster.

Handling of concurrent requests – Another key functionality of Node is the ability to handle concurrent connections with a very minimal overhead on a single process.

The Node.js library uses JavaScript – This is another important aspect of development in Node.js. A major part of the development community is already well versed in javascript, and hence, development in Node.js becomes easier for a developer who knows javascript.

There is an active and vibrant community for the Node.js framework.

Because of the active community, there are always keys updates made available to the framework. This helps to keep the framework always up-to-date with the latest trends in web development.

Node.js is used by many large companies. Below is a list of a few of them. Paypal – A lot of sites within Paypal have also started the transition onto Node.js.

Features of Node.js

LinkedIn – LinkedIn is using Node.js to power their Mobile Servers, which powers the iPhone, Android, and Mobile Web products. Mozilla has implemented Node.js to support browser APIs which has half a billion installs.

eBay hosts their HTTP API service in Node.js. Node.js is best for usage in streaming or event-based real-time applications like.

When to not use Node.js

Chat applications. Game servers – Fast and high-performance servers that need to processes thousands of requests at a time, then this is an ideal framework.

Good forcollaborative environment – This is good for environments which manage documents. In a document management environment, you will have multiple people who post their documents and do constant changes by checking out and checking in documents.

So Node.js is good for these environments because the event loop in Node.js can be triggered whenever documents are changed in a document managed environment.

Advertisement servers – Again here you could have thousands of request to pull advertisements from the central server and Node.js can be an ideal framework to handle this.

Streaming servers – Another ideal scenario to use Node is for multimedia streaming servers wherein clients have request’s to pull different multimedia contents from this server.

Node.js is good when you need high levels of concurrency but less amount of dedicated CPU time.

Best of all, since Node.js is built on javascript, it’s best suited when you build client-side applications which are based on the same javascript framework. Node.js can be used for a lot of applications with various purposes.

The only scenario where it should not be used is where there are long processing times, which is required by the application.

Node is structured to be single-threaded. If an application is required to carry out some long-running calculations in the background, it won’t be able to process any other requests.

As discussed above, Node.js is used best where processing needs less dedicated CPU time.

Installing on Node.js on Windows or on Windows Subsystem for Linux. Open your command line and create a new directory: mkdir HelloNode, then enter the directory: cd HelloNode.

Create a JavaScript file named "app.js" with a variable named "msg" inside: echo var msg > app.js. Open the directory and your app.js file in VS Code using the command: code .

Add a simple string variable ("Hello World"), then send the contents of the string to your console by entering this in your "app.js" file:.

To run your "app.js" file with Node.js. Open your terminal right inside VS Code by selecting View > Terminal (or select Ctrl+`, using the backtick character).

If you need to change the default terminal, select the dropdown menu and choose Select Default Shell. In the terminal, enter: node app.js. You should see the output: "Hello World".

Notice that when you type console in your 'app.js' file, VS Code displays supported options related to the console object for you to choose from using IntelliSense.

Node.js Syllabus

Try experimenting with Intellisense using other JavaScript objects.

  • Open your command line (Command Prompt, Powershell, or whatever you prefer).
  • Create a new project folder: mkdir ExpressProjects and enter that directory: cd ExpressProjects.

  • Use Express to create a HelloWorld project template: npx express-generator HelloWorld --view=pug.
  • We are using the npx command here to execute the Express.js Node package without actually installing it (or by temporarily installing it depending on how you want to think of it).

  • If you try to use the express command or check the version of Express installed using: express --version, you will receive a response that Express cannot be found.
  • If you want to globally install Express to use over and over again, use: npm install -g express-generator.

    You can view a list of the packages that have been installed by npm using npm list.

  • They'll be listed by depth (the number of nested directories deep).

Packages that you installed will be at depth 0. That package's dependencies will be at depth 1, further dependencies at depth 2, and so on.

  1. To learn more, see Difference between npx and npm?
  2. on StackOverflow. Examine the files and folders that Express included by opening the project in VS Code, with: code .

  3. The files that Express generates will create a web app that uses an architecture that can appear a little overwhelming at first.
  4. You'll see in your VS Code Explorer window (Ctrl+Shift+E to view) that the following files and folders have been generated:.

  5. Contains the executable file that starts your app.
  6. It fires up a server (on port 3000 if no alternative is supplied) and sets up basic error handling.

    Contains all the publicly accessed files, including JavaScript files, CSS stylesheets, font files, images, and any other assets that people need when they connect to your website.

  7. Contains all the route handlers for the application.

Two files, index.js and users.js, are automatically generated in this folder to serve as examples of how to separate out your application’s route configuration.

Contains the files used by your template engine. Express is configured to look here for a matching view when the render method is called.

The default template engine is Jade, but Jade has been deprecated in favor of Pug, so we used the --view flag to change the view (template) engine.

You can see the --view flag options, and others, by using express --help.

The starting point of your app.

It loads everything and begins serving user requests.

It's basically the glue that holds all the parts together. Contains the project description, scripts manager, and app manifest.

Its main purpose is to track your app's dependencies and their respective versions.

Useful Video Courses

You now need to install the dependencies that Express uses in order to build and run your HelloWorld Express app (the packages used for tasks like running the server, as defined in the package.json file).

Inside VS Code, open your terminal by selecting View > Terminal (or select Ctrl+`, using the backtick character), be sure that you're still in the 'HelloWorld' project directory. Install the Express package dependencies with:. At this point you have the framework set up for a multiple-page web app that has access to a large variety of APIs and HTTP utility methods and middleware, making it easier to create a robust API.

Start the Express app on a virtual server by entering:.

The DEBUG=myapp:* part of the command above means you are telling Node.js that you want to turn on logging for debugging purposes.

Remember to replace 'myapp' with your app name.

You can find your app name in the package.json file under the "name" property.

Using npx cross-env sets the DEBUG environment variable in any terminal, but you can also set it with your terminal specific way.

The npm start command is telling npm to run the scripts in your package.json file.

You can now view the running app by opening a web browser and going to: localhost:3000. Now that your HelloWorld Express app is running locally in your browser, try making a change by opening the 'views' folder in your project directory and selecting the 'index.pug' file.

Once open, change h1= title to h1= "Hello World!"

and selecting Save (Ctrl+S). View your change by refreshing the localhost:3000 URL on your web browser.

To stop running your Express app, in your terminal, enter: Ctrl+C.

In your command line, open the Node.js CLI. You'll see the > prompt letting you know you're using Node.js after entering: node. To identify the operating system you are currently using (which should return a response letting you know that you're on Windows), enter: os.platform(). To check your CPU's architecture, enter: os.arch().

To view the CPUs available on your system, enter: os.cpus(). Leave the Node.js CLI by entering .exit or by selecting Ctrl+C twice.

You can use the Node.js OS module to do things like check the platform and return a platform-specific variable: Win32/.bat for Windows development, darwin/.sh for Mac/unix, Linux, SunOS, and so on (for example, var isWin = process.platform"win32";).

const http = require("http");
const hostname ="localhost";
const port =3000;
const server = http.createServer((req, res)=>{
res.statusCode=200;
res.setHeader("Content-Type","text/html");
res.end(
"

This is a HTML response

  1. One
  2. Two
  3. Three
"
);
});
server.listen(port, hostname,()=>{
console.log(`Server running at http://${hostname}:${port}/`);
});

When you run this code, you should see the following response.

Awesome.

Let’s go ahead and create different routes to support multiple responses.

Check out the code shown below.

const http = require("http");
const hostname ="localhost";
const port =3000;
const server = http.createServer((req, res)=>{
res.statusCode=200;
res.setHeader("Content-Type","text/html");
switch(req.url){
case"/home":
res.writeHead(200);
res.end("");
break;
case"/about":
res.writeHead(200);
res.end("");
break;
default:
break;
}
});
server.listen(port, hostname,()=>{
console.log(`Server running at http://${hostname}:${port}/`);
});

As you can see, we are using switch cases to determine different routes and on each route, we are sending different responses to each route.

Navigate your browser to localhost:3000/home to view the response.

Navigate your browser to localhost:3000/about to view the second response.

Awesome. We built a simple web server in Node. Let’s jump to the next step.

Why use Node.js?

Node modules are the basic building block of the Node program.

The node module is a set of functions that can be reused in your application.

Node has built-in modules as well as you can create your node modules.

Some of the famous built-in node modules are fs, net, http, and many of the popular modules such as express, nodemailer built on top of these built-in modules.

We can install node modules using the node package manager or called npm.

You can install node modules using the following command.

Open your terminal/command prompt and run this command.

Or

For example:

You can also install the module and write it in your package.json file using the following command.

Or

You can use the following command to uninstall node modules.

If you want to remove the module entry from the package.json file, use this command.

You can create your own node module as well. All you need to do is create a function and export it for the reusability.

For example, consider this code which can act as a node module.

const calc =(a,b,p)=>{
if(a || b || p ){
return"Please provide all parameters";
}
switch(p){
case'+':{
return a+b;
break;
}
case'-':{
return a-b;
break;
}
case'*':{
return a*b;
break;
}
case'/':{
return a/b;
break;
}
default:{return;}
}
}
exports.calc=calc;//very important line

You can reuse this module in your code like this:

var dt = require('./mymodule');
console.log(dt.calc(10,20,'+'));

This is a really simple example. However, this gives an idea about how to create node modules. If you are interested in more detailed information, visit this tutorial.

Node modules are managed by the file called package.json. This file contains the list of the packages your project is using along with the version number etc.

A typical package.json file looks like this:

{
"name":"codeforgeek-app-server",
"version":"1.0.0",
"description":"",
"main":"app.js",
"scripts":{
"start":"node app.js"
},
"keywords":[],
"author":"",
"license":"ISC",
"dependencies":{
"async":"^3.1.0",
"axios":"^0.19.0",
"bcrypt":"^4.0.1",
"chalk":"^2.4.2",
"connect-redis":"^4.0.4",
"cors":"^2.8.5",
"express":"^4.17.1",
"mongodb":"^3.2.7",
"nconf":"^0.10.0",
"nodemailer":"^6.3.0",
"pug":"^2.0.4",
"reading-time":"^1.2.0",
"redis":"^2.8.0",
"winston":"^3.2.1"
}
}

We also specify details such as project name, version, entry file of the project in the package.json.

All the dependencies that are installed using npm install command are listed in the package.json. You should always maintain the updated version of package.json while dealing with the packages.

Let’s jump to the next step.

Node.js Interview Questions & Tutorial PDF

The fs module provides an API for interacting with the file system of your operating system. To use this module, require it in your code like this:

There are lots of methods provided under this node module to perform various tasks such as creating files, writing data into a file, reading data from files, etc.

You can use fs.readFile() or fs.readFileSync() method to read files in Node.

For example: Using the readFile() method.

const fs = require('fs');
fs.readFile('./lorem.txt',(err, data)=>{
if(err){
return console.log('Error occurred while reading file');
}
console.log(data.toString());
});

Using the readFileSync() method.

const fs = require('fs');
const data = fs.readFileSync('./lorem.txt'); console.log(data.toString());

The simplest approach to check whether the file exists or not is by using the readFile() function.

However, this function does open the file descriptor and occupies some memory too.

If you just want to check the file existences in the system, I highly recommend the access() function. Here is the code:

const fs = require('fs');
const path ='./config.js';
fs.access(path, fs.F_OK,(err)=>{
if(err){
console.error(err);
return;
}
});

The file system module provides three methods to create files:

  1. fs.open()
  2. fs.writeFile()
  3. fs.appendFile()

fs.open() method opens a new file or creates a new empty file if it does not exist in the specified path.

It takes the second parameter which acts as a flag such as w for writing, w+ for reading and writing, etc. Code:

const fs = require('fs');
fs.open('file.txt','w',(err, file)=>{
if(err){
throw err;
}
console.log('Saved!');
});

fs.writeFile() method allows you to create or replace files with the content.

If a file exists, it will replace the content with the provided content and if the file does not exist, it will create it.

const fs = require('fs');
fs.writeFile('file.txt','Hello Word!',(err)=>{
if(err){
throw err;
}
console.log('Saved!');
});

fs.appendFile() method appends the provided content at the end of the file.

const fs = require('fs');
fs.appendFile('file.txt',' Hello World',(err)=>{
if(err){
throw err;
}
console.log('Updated!');
});

To delete a file, we can use fs.unlink() method.

const fs = require('fs');
fs.unlink('file.txt',(err)=>{
if(err){
throw err;
}
console.log('File deleted!');
});

To rename a file, we can use the fs.rename() method.

const fs = require('fs');
fs.rename('newfile.txt','oldfile.txt',(err)=>{
if(err){
throw err;
}
console.log('File Renamed!');
});

You can also copy files using the fs.copy() method.

const fs = require('fs');
fs.copyFile(file.txt', 'copyfile.txt', (err) => {
if (err) {
throw err;
}
console.log('File is copied!');
});

Let’s jump to the next step.

Node.js Basics for Beginners

Express is a popular framework to develop web applications in Node.

Express is widely used and can be used to develop web applications such as Web Server, REST API Server, Streaming engine, etc.

In this section, we are going to learn about express and we will create a simple web server with different routes.

Terminologies we will use in this section are:

  1. route: This means an endpoint. for example facebook.com/profile so the profile is a route.
  2. middleware: A set of functions that will be executed in the chosen order.

Let’s begin.

Create a new folder and switch to it using a terminal or command prompt.

Create a new node project using the following command.

This will create a sample package.json for your project. To install the express module, run the following command.

The latest version of the express framework will be installed in your project. Now create a new file and name it app.js. In this file, we will write our web server using express.

const express = require('express');
const app = express();
app.listen(process.env.port||3000);
console.log('Web Server is listening at port '+(process.env.port||3000));

In the code shown above, we have required the express module and created a new instance of it.

In the end, we have started our Server using the listen() function.

Routers are simply an endpoint of a server.

For example, facebook.com/codeforgeek, here the codeforgeek is a route.

We need to create routers in our web application to serve different requests. We will create the following routes in our web application.

  1. home
  2. profile
  3. login
  4. logout

Express routers allow us to serve different HTTP methods such as GET, POST, PUT, DELETE, HEAD. Here is how to create a router.

const express = require('express');
const app = express();
const router = express.Router();
router.get('/home',(req,res)=>{
res.send('Hello World, This is home router');
});
router.get('/profile',(req,res)=>{
res.send('
Hello World, This is profile router
');
});
router.get('/login',(req,res)=>{
res.send('
Hello World, This is login router
');
});
router.get('/logout',(req,res)=>{
res.send('
Hello World, This is logout router
');
});
app.use('/', router);
app.listen(process.env.port||3000);
console.log('Web Server is listening at port '+(process.env.port||3000));

Let’s run our application, save the file, and run the code using the following command.

You should see the following message in the terminal.

Open your browser and visit the routes.

Here is the profile page.

You can also send HTML/JSON/XML as a response.

Express provides middleware function support. Middleware functions as the name suggests can be used to make changes in the request/response lifecycle of the express. There are five types of middleware functions in the express.

  • Application middleware
  • Router middleware
  • Error-handling middleware
  • Built-in middleware
  • Third-party middleware

Node.js Advance Stuff!

We can use middleware in the application object of the express. For example:

const express = require('express');
const app = express();
app.use((req, res, next)=>{
console.log('Time:',Date.now());
next();
});
app.listen(process.env.port||3000);
console.log('Web Server is listening at port '+(process.env.port||3000));

Know the Difference!

In a similar way as application middleware, we can use router middleware. For example:

const express = require('express');
const app = express();
const router = express.Router();
router.use((req, res, next)=>{
console.log('Time:',Date.now());
next();
});
router.get('/home',(req,res)=>{
res.send("ok")
});
app.use('/', router);
app.listen(process.env.port||3000);
console.log('Web Server is listening at port '+(process.env.port||3000));

error-handling middleware

We can use this middleware to catch errors.

app.use((err, req, res, next)=>{
res.status(500).send('Something broke!')
});

Learn more about this function here.

Built-in middleware

Express provides some middleware by default such as static, JSON, etc.

Third-party middleware

We can use third-party middlewares such as body-parser. Here is how we can install third-party middleware.

To use this middleware, we need to require our code and load it.

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = express.Router();
router.get('/home',(req,res)=>{
res.send('
Hello World, This is home router
');
});
router.get('/profile',(req,res)=>{
res.send('
Hello World, This is profile router
');
});
router.get('/login',(req,res)=>{
res.send('
Hello World, This is login router
');
});
router.get('/logout',(req,res)=>{
res.send('
Hello World, This is logout router
');
});
// add middleware before routes
app.use(bodyParser.json());
app.use('/', router);
app.listen(process.env.port||3000);
console.log('Web Server is listening at port '+(process.env.port||3000));

If you are interested in creating your middleware, I recommend you this article.

We can handle sessions in Express using express-session middleware. We can use this middleware to create, track, and delete sessions.

To use this module in our code, load this as a middleware.

Now, we can use req.session object to create, track, and delete sessions.

To learn more about the session, please read this article.

We can also use external stores such as Redis to store session values instead of storing them in memory.

Let’s jump to the next step and learn about the integration of databases with Node.

Step 6: Databases – MySQL, MongoDB, PostgreSQL and Redis.

The database is an integral part of any application. You must know how to use it with Node to build a complete application.

We are going to cover the following databases in this section:

  • MySQL
  • MongoDB
  • PostgreSQL
  • Redis

Let’s begin with MySQL.

MySQL

MySQL is a very popular SQL database. In this section, we will learn how to connect, query, and use it with NodeJS.

MySQL is a very popular database and has been used in millions of applications. We can use MySQL with Node as well.

We need to install the module name as MySQL to use it with the MySQL database.

You need to have the MySQL database installed in your system before proceeding.

To install the node module to connect with MySQL:

Here is how we can establish a connection to the MySQL engine.

const mysql = require("mysql");
const pool = mysql.createPool({
connectionLimit:100,
host:"localhost",
user:"root",
password:"",
database:"database_name",
debug:false,
});
pool.query("SELECT * from LIMIT 10",(err, rows)=>{
if(err){
console.log("error occurred during the connection.");
}
console.log(rows[0]);
});

You can execute the queries such as INSERT, UPDATE and DELETE in a similar fashion. Learn more in detail about using Node and MySQL.

Let’s learn about MongoDB.

MongoDB

MongoDB is a very popular NoSQL database. Learn how to connect, query, and use it with NodeJS.

MongoDB is one of the most popular general-purpose NoSQL database engines.

To integrate MongoDB with Node, you need to install the MongoDB database in your system.

Click here to visit the official site and download the latest version of MongoDB.

Assuming you have MongoDB installed, let’s install the MongoDB driver for Node.

We need to require the module and then connect to the MongoDB instance. Here is the code.

const mongo = require("mongodb");
const url ="mongodb://localhost:27017/test";
mongo.connect(url,{ useNewUrlParser:true},(err, db)=>{
if(err){
console.log(err);
process.exit(0);
}
console.log("database connected!");
db.close();
});

MongoDB runs on port 27017. We can connect to any database we like to work with.

In the code shown above, we are connecting to the test database.

We are using the connect() method to establish a connection with the database. Save the code above in a file called ‘app.js’ and run the file:

You should see output similar to this:

In order to store data in the MongoDB database you need to create a collection.

Think of collection as a table in the SQL database. You can either create a collection in the MongoDB shell or you can do it in code. Here is how you can do it in code.

const mongo = require("mongodb");
const url ="mongodb://localhost:27017/";
mongo.connect(url,{ useNewUrlParser:true},(err, db)=>{
if(err){
console.log(err);
process.exit(0);
}
console.log("database connected!");
var dbo = db.db("test");
dbo.createCollection("customers",(err, result)=>{
if(err){
console.log(err);
process.exit(0);
}
console.log("collection created!");
db.close();
});
});

Let’s try to add some data in the MongoDB collection.

MongoDB stores data in a JSON format. JSON is a key-value based data format widely used across various layers of software.

const mongo = require("mongodb");
const url ="mongodb://localhost:27017/";
mongo.connect(url,{ useNewUrlParser:true},(err, db)=>{
if(err){
console.log(err);
process.exit(0);
}
let data ={ id:100, name:"Shahid"};
var dbo = db.db("test");
console.log("database connected!");
dbo.collection("user").insert(data,(err, result)=>{
if(err){
console.log(err);
process.exit(0);
}
console.log("records added.");
console.log(result);
db.close();
});
});

You can also search for the data inside the collection using the findOne() function.

const mongo = require("mongodb");
const url ="mongodb://localhost:27017/";
mongo.connect(url,{ useNewUrlParser:true},(err, db)=>{
if(err){
console.log(err);
process.exit(0);
}
let data ={ id:100, name:"Shahid"};
var dbo = db.db("test");
console.log("database connected!");
dbo.collection("user").findOne({},(err, result)=>{
if(err){
console.log(err);
process.exit(0);
}
console.log("Here is the record");
console.log(result);
db.close();
});
});

After running the code above, you should see a record similar to this.

You can also perform tons of other operations such as query(), sort(), delete() etc. Learn more about MongoDB here.

Let’s proceed towards the next database, PostgreSQL.

PostgreSQL

PostgreSQL is a very popular SQL database. Learn how to connect, query, and use it with NodeJS.

PostgreSQL, also referred to as Postgres, is a free and popular relational database system.

Postgres competes with relational databases like MySQL, SQL Server, or MariaDB.

You need to have Postgres installed in your system to continue with this tutorial. Visit the official download page to install Postgres to grab a copy and install Postgre in your system.

We need to create a user credential in Postgres in order to connect to the database. Connect to Postgres using the default credentials. Run this command in your terminal.

Create a new user.

CREATEROLE codeforgeek WITH LOGIN PASSWORD 'somepassword'

Give permission to the new user.

Now, exit from the current session and login again with your new user credentials.

Create a new database.

Switch to a new database.

Create a new table.

users=>CREATETABLE profile (
ID SERIAL PRIMARYKEY,
name VARCHAR(30),
email VARCHAR(30)
);

Insert some records.

INSERT
INTO profile (name, email)
VALUES
('Jerry','[email protected]'),
('George','[email protected]');

Let’s connect to it using our Node program. Install the dependency.

Create an app.js file and add the following code in it.

const Pool = require("pg").Pool;
const pool =new Pool({
user:"codeforgeek",
host:"localhost",
database:"users",
password:"somepassword",
port:5432,
});
// read information from table
pool.query("SELECT * FROM profile ORDER BY id ASC",(error, results)=>{
if(error){
console.log(error);
return;
}
console.log(results);
});
// add a new user profile.
const name ="Shahid";
const email ="[email protected]";
pool.query(
"INSERT INTO profile (name, email) VALUES ($1, $2)",
[name, email],
(error, results)=>{
if(error){
console.log(error);
return;
}
console.log(results);
}
);

We created a new Pool connection to Postgres. We first executed a SELECT query using the pool.query() method. The pool connection automatically returns the connection to the pool after executing the query.

Let’s proceed towards the final database in the section.

Redis

Redis is the high-performance in-memory database used as a data structure store. Redis supports hash, strings, lists, and other complicated data structures by maintaining very high performance.

Redis along with Node.js can be used to solve various problems such as cache server or message broker.

You can install Redis in your system by following the official installation guides.

Once installed, you can run the Redis server using the following command.

You should see the following in your terminal.

To access the Redis command-line interface, run the following command from a separate terminal.

To configure Redis with Node, we need to install the Redis driver.

Here is the sample code to connect to the Redis server.

var redis = require('redis');
var redisClient = redis.createClient({host :'localhost', port :6379});
redisClient.on('ready',function(){
console.log("Redis is ready");
});
redisClient.on('error',function(){
console.log("Error in Redis");
});

When you run this command, you should have a connection with the Redis.

You can use set(), get() and other Redis commands to perform various operations.

To dig deeper into Redis, you can visit this tutorial.

Step 7: Deploying Node application to a Cloud Server

Let’s learn how to deploy our Node application. I deploy all my projects on DigitalOcean. I highly recommend it to developers. If you have never tried DigitalOcean, give it a shot with a $10 discount for the first month.

Click here to go to the DigitalOcean droplet creation screen.

Choose a $5 plan and create the droplet. After creating a droplet wait for some time, DigitalOcean will send you an email containing the credentials. Login to your droplet using the following command.

Provide the password given in the email and you are good to go.

Once you are logged in, update the system using the following command.

Install Git.

Install the latest Node on your Server.

curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -

sudo apt-get install -y nodejs

Install the PM2 process manager.

Our server is ready to host our Node applications.

Github is a code hosting platform. Learn how to host your code in the Github platform.

Let’s push our code to Github. Go to Github.com and create a new repository.

Copy the repository path. Assuming you have Git installed in your machine. Switch to the project directory and execute these commands one by one.

git init
git add .
git commit - m "first push"
git remote add origin << github repo URL >>
git push origin master

Login to your server using SSH.

Clone the Github project.

Switch to the project directory.

Install dependencies.

Run the Node project using PM2.

PM2 is a process management tool for Node. Using PM2 we can ensure 99% uptime of your application.

Test your application using Droplet IP and port on which your application is running.

Awesome. You have successfully developed and deployed your application. Here is another article related to deployment of application in the production server.

Download this tutorial in a PDF format

I have created a PDF format of this Node js tutorial for beginners. You can visit this page to download the book.

Further Study

We have written a lot of Node js tutorials on different topics, listing some of the best articles for you to read it further.

Building Email Verification System Using Node and Redis
Microservices Architecture with Node.js
Load Balancing Node.js Application Servers with Nginx
Building a URL Shortener with Node.Js and Redis
Load Balancing Node.js Application Servers with Nginx