Why You Should Learn Node And ExpressJs

sarthaksavvy

๐’ฎ๐’ถ๐“‡๐“‰๐’ฝ๐’ถ๐“€ ๐Ÿ“จ

Posted on August 30, 2022

Why You Should Learn Node And ExpressJs

Watch the full Nodejs and ExpressJsTutorial on Youtube

Nodejs Introduction

So node.js is firstly not a language it's not a framework it's a free and open source runtime for javascript. Now what is the runtime and how it's different from the javascript engine, so the javascript engine just executes the code but the runtime environment just like node.js has some additional server-side modules in node.js. the node.js is able to run the javascript code onto the server and this is the breakthrough because now this is the first time node.js can run the javascript or anything can run the javascript on the server.

Node.js uses asynchronous programming!

But Q) what is asynchronous ?

think.webp

here is difference between asynchronous and synchronous

download.png

download (1).png

Q)Why Node.js?

-> A common task for a web server can be to open a file on the server and return the content to the client.

This is how Node.js handles a file request:

1. Sends the task to the computer's file system.

2. Ready to handle the next request.

3. When the file system has opened and read the file, the server returns the content to the client.

Node.js eliminates the waiting and simply continues with the next request.

Node.js runs single-threaded, non-blocking, asynchronous programming, which is very memory efficient.

What Can Node.js Do?

  • Node.js can generate dynamic page content
  • Node.js can create, open, read, write, delete, and close files on the server
  • Node.js can collect form data
  • Node.js can add, delete, modify data in your database

Screenshot (53).png

How to Install Nodejs

The official Node.js website has installation instructions for Nodejs:

or You can Watch Here

Creating Your First server

const http = require('node:http');

// Create a local server to receive data from
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    data: 'Hello World!'
  }));
});

server.listen(3000);
Enter fullscreen mode Exit fullscreen mode

*Output *
Screenshot (56).png

Node.js Modules

Q)What is a Module in Node.js?

=> Consider modules to be the same as JavaScript libraries.

  • A set of functions you want to include in your application.

Built-in Modules

Node.js has a set of built-in modules which you can use without any further installation.

Look at the Built-in Modules Reference for a complete list of modules.

Include Modules

To include a module, use the require() function with the name of the module:

let http = require('http');
// Now your application has access to the HTTP module, and is able to create a server:
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('Hello World!');
}).listen(3000);
Enter fullscreen mode Exit fullscreen mode
Create Your Own Modules

Watch here

You can create your own modules, and easily include them in your applications.

The following example creates a module that returns a date and time object:

Create a module that returns the current date and time:

exports.myDateTime = function () {
  return Date();
};
Enter fullscreen mode Exit fullscreen mode

Use the **exports* keyword to make properties and methods available outside the module file.*

Save the code above in a file called "myfirstmodule.js"

Including Your Own Module

Now you can include and use the module in any of your Node.js files.

// Use the module "myfirstmodule" in a Node.js file:

let http = require('http');
let dt = require('./myfirstmodule');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write("The date and time are currently: " + dt.myDateTime());
  res.end();
}).listen(3000);

// Notice that we use ./ to locate the module, that means that 
// the module is located in the same folder as the Node.js file.
Enter fullscreen mode Exit fullscreen mode

Global objects

Watch here

These objects are available in all modules. The following variables may appear to be global but are not. They exist only in the scope of modules:

  • __dirname
  • __filename
  • exports
  • module
  • require()

The objects listed here are specific to Node.js. There are built-in objects that are part of the JavaScript language itself, which are also globally accessible.

Node.js package.json field definitions

Wacth Here

This section describes the fields used by the Node.js runtime. Other tools (such as npm) use additional fields which are ignored by Node.js.

The following fields in package.json files are used in Node.js:

  1. "name"
  2. "main"
  3. "packageManager"
  4. "type"
  5. "exports"
  6. "imports"

nodemon

nodemon is a tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected.

Install

Watch here

npm i nodemon
Enter fullscreen mode Exit fullscreen mode

File System Modules

Watch Here

fs.readFile(path[, options], callback)

Asynchronously reads the entire contents of a file.

import { readFile } from 'node:fs';

readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
});
Enter fullscreen mode Exit fullscreen mode

The callback is passed two arguments (err, data), where data is the contents of the file. If no encoding is specified, then the raw buffer is returned. If the option is a string, then it specifies the encoding:

import { readFile } from 'node:fs';

readFile('/etc/passwd', 'utf8', callback);
Enter fullscreen mode Exit fullscreen mode

Nodejs Event Loop

Watch here

Weโ€™ve finally reached the infamous Event Loop. This is a constantly running process that checks if the call stack is empty. Imagine it like a clock and every time it ticks it looks at the Call Stack and if it is empty it looks into the Event Queue. If there is something in the event queue that is waiting it is moved to the call stack. If not, then nothing happens.

ek7ji4zrimozpp2yzk0a.webp

gif3.1.gif

gif4.gif

Graphic credit:- Lydia Hallie

ExpressJS

Express is a node js web application framework that provides broad features for building web and mobile applications.It is used to build a single page, multipage, and hybrid web application. It's a layer built on top of the Node js that helps manage servers and routes

Installation

Watch Here

$ npm install express --save
Enter fullscreen mode Exit fullscreen mode
const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})
//This app starts a server and listens on port 3000 
//for connections.The app responds with โ€œHello World!โ€ 
//for requests to the root URL (/) or route.
Enter fullscreen mode Exit fullscreen mode

Basic Routing in ExpressJs

Watch Here

//Respond with Hello World! on the homepage:
app.get('/', (req, res) => {
  res.send('Hello World!')
});

//Respond to POST request on the home page:
app.post('/', (req, res) => {
  res.send('Got a POST request')
});

//Respond to a PUT request to the /user route:
app.put('/user', (req, res) => {
  res.send('Got a PUT request at /user')
});

//Respond to a DELETE request to the /user route:
app.delete('/user', (req, res) => {
  res.send('Got a DELETE request at /user')
});
Enter fullscreen mode Exit fullscreen mode

Connect With MongoDB

Watch here

Q)What is Controller?

=> controller is just going to handle the request and do the stuff that is required, route file is not responsible for all these things it should be done in the controller.

Watch here

const { ObjectId } = require("mongodb");
const Book = require("../models/Book");

exports.index = async (req, res) => {
  const books = await Book.find();
  res.json(books);
};

exports.store = async (req, res) => {
  try {
    await Book.create(req.body);
    res.status(201).json({ data: "Book is stored" });
  } catch (error) {
    res.json(error.errors);
  }
};

exports.show = async (req, res) => {
  const _id = ObjectId(req.params.id);
  const book = await Book.find({ _id });
  res.json(book);
};

exports.udpate = async (req, res) => {
  const _id = ObjectId(req.params.id);
  await Book.updateOne({ _id }, { $set: req.body });
  res.json({ data: "Book is updated" });
};

exports.delete = async (req, res) => {
  const _id = ObjectId(req.params.id);
  await Book.deleteOne({ _id });
  res.status(204).json();
};
Enter fullscreen mode Exit fullscreen mode

we can see everything we are doing every time we need to connect with the database and every time we need to find which collection we need to work on and that's not a bad thing but we can improve over it for that to have the connection directly with the MongoDB we are going to use another package called mongoose

install Mongoose

Watch Here

npm i mongoose
Enter fullscreen mode Exit fullscreen mode

use the mongoose to connect with the database, not the normal MongoDB connection once that is done then you need to define some** model** now Q)what is a model actually a file or a class you can say which is directly connected to a single collection so if I create a blog post, model, that model will be responsible for the blog post collection or think about blog post table and we need to define each and every field on that's what we are doing here.

const { mongoose } = require("mongoose");

const BookSchema = mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  author: {
    type: String,
    required: true,
  },
});

module.exports = mongoose.model("Book", BookSchema, "book");
Enter fullscreen mode Exit fullscreen mode

How to make SignUp and LoginUp Authentication in Node and Expressjs

Wacth Here for better Understanding

const User = require("../models/User");
const bcrypt = require("bcrypt");
var jwt = require("jsonwebtoken");
const saltRounds = 10;

exports.signup = async (req, res) => {
  const password = await bcrypt.hash(req.body.password, saltRounds);
  const data = { ...req.body, password };
  const user = await User.create(data);
  res.json({ user });
};

exports.login = async (req, res) => {
  const user = await User.findOne({ email: req.body.email });
  if (!user) {
    res.status(404).json({ error: "User not found" });
    return;
  }

  if (!(await bcrypt.compare(req.body.password, user.password))) {
    res.status(404).json({ error: "User not found" });
    return;
  }

  const token = await jwt.sign({ user }, "fake-jwt-secret");
  res.json({ user, access_token: token });
};
Enter fullscreen mode Exit fullscreen mode

JWT Access Token

JSON Web Token is a proposed Internet standard for creating data with optional signature and/or optional encryption whose payload holds JSON that asserts some number of claims. The tokens are signed either using a private secret or a public/private key.

install

Watch Here

npm i jsonwebtoken
Enter fullscreen mode Exit fullscreen mode

MiddleWare

Watch Here

The Middleware is like a guard which will protect the code to execute on the further or not so it will say okay something is good then go again but if something is bad stop here

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack

Screenshot (58).png

JWT Authorisation

Watch Here

the normal flow for any authorization is like first we call the user we get the user token like this, we copy that token and then after this, we can go to any protected route if we send the query right, it says unauthorized 401 but we need to send the authentication token or authorization token as like bearer and whatever the token is now if I send it should give us the real content because now we have the valid token but how do we check for the token first.

That's All you need to know about Nodejs and Expressjs

finally.webp

So Far We have learned a lot. Do ask questions for clarifications and make corrections & suggestions, I expect them. That is all from my end, please share your views in the comment section, and thanks for reading it. Check out my other article Here. Also, Subscribe to my newsletter. Follow me on Socials. Happy Learning and Coding

200w (1).webp

Subscribe To My YouTube channel

Follow me on Twitter

THANK YOU SO MUCH FOR YOUR TIME

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About