2 Node JS Part 2
2 Node JS Part 2
2
Node.JS: Var
▷ The JavaScript variables statement is used to declare a variable and, optionally, we can
initialize the value of that variable.
▷ Example: var a =10;
▷ Variable declarations are processed before the execution of the code.
▷ The scope of a JavaScript variable declared with var is its current execution context.
▷ The scope of a JavaScript variable declared outside the function is global.
3
Problem with var
▷ var variables can be re-declared and updated
if (times > 3) {
var greeter = "say Hello instead";
}
https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/ 4
Further Reading
https://www.geeksforgeeks.org/difference-between-var-let-and-const-keywords-in-javasc
ript/
https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/
5
Node.JS: let
▷ The let statement declares a local variable in a block scope. It is similar to var, in that
we can optionally initialize the variable.
▷ Example: let a =10;
○ The let statement allows you to create a variable with the scope limited to the
block on which it is used.
○ It is similar to the variable we declare in other languages like Java, .NET, etc.
6
Node.JS: Const
▷ const statement values can be assigned once and they cannot be reassigned.
▷ The scope of const statement works similar to let statements.
7
Modules
▷ In node you have this concept called module.
▷ Every file in Node is a Module. Functions and variables inside those modules are only
part of that file.
▷ Similar to private in OOP. If you want to access this outside of the module, you have to
explicitly export these items.
8
HTTP Module
▷ Node.js has a built-in module called HTTP, which allows Node.js to transfer data over
the Hyper Text Transfer Protocol (HTTP).
▷ To include the HTTP module, use the require() method
▷ The HTTP module can create an HTTP server that listens to server ports and gives a
response back to the client.
▷ Use the createServer() method to create an HTTP server
9
10
Path module
▷ The path module provides utilities for working with file and directory paths.
▷ var path=require('path');
11
12
OS Module
▷ Provides information about the computer's operating system.
▷ var os=require('os');
13
14
File systems
▷ Work with the file system on your computer.
▷ var fs = require('fs');
15
16
Create your own module
▷ A module that will return date
References
https://www.w3schools.com/nodejs/nodejs_modules.asp
https://www.digitalocean.com/community/tutorials/how-to-create-a-node-js-module
17
▷ Create a folder name “whatsthedate”
▷ Run “npm init” in the folder
▷ Give required data
▷ It will create package.json file
18
19
20
▷ Create index.js file inside the package directory
21
▷ Edit your app.js file
22
Node.js Frameworks and Tools
“Node.js is a low-level platform. In order to make things easy and exciting for developers,
thousands of libraries were built upon Node.js by the community.”
~nodejs.dev/learn~
23
Express JS
▷ “Fast, unopinionated, minimalist web framework for Node.js”
▷ https://expressjs.com/
▷ npm install express --save
24
-- save
▷ Add to dependencies in package.json file
25
26
27
Express Routing
})
28
const express=require('express');
const app = express();
const port=8080;
app.get('/',(req,res)=>{
res.send("ExpressJS Hello World!")
})
app.get('/test',(req,res)=>{
res.send("Test GET route")
})
app.post('/test',(req,res)=>{
res.send("Test POST route")
})
app.listen(port,()=>{
console.log(`App running on port ${port}`)
})
29
30
Routers
▷ Defining the routes in app.js file is difficult to maintain
▷ We can user express.Router() to separate routes from app.js file
31
users.js
var express = require('express');
var router = express.Router();
module.exports = router;
32
app.js
const express=require('express');
const app = express();
const port=8080;
const users=require('./users');
app.use('/users',users);
app.listen(port,()=>{
console.log(`App running on port ${port}`)
})
33
Express URL building
▷ In users.js file
router.get('/:id',function (req,res){
res.send('User ID is '+req.params.id);
});
34
Middleware
▷ Middleware functions are functions that have access to the request object (req), the
response object (res), and the next function in the application’s request-response cycle.
▷ The next function is a function in the Express router which, when invoked, executes the
middleware succeeding the current middleware.
35
Middleware cont
▷ Execute any code.
▷ Make changes to the request and the response objects.
▷ End the request-response cycle.
▷ Call the next middleware in the stack.
https://expressjs.com/en/guide/writing-middleware.html
36
middleware.js
logtime = (req,res,next)=>{
console.log(Date.now());
next();
}
module.exports={
logtime:logtime
}
37
app.js
const express=require('express');
const middleware=require('./middleware');
const app = express();
const port=8080;
const users=require('./users');
app.use(middleware.logtime);
app.use('/users',users);
app.listen(port,()=>{
console.log(`App running on port ${port}`)
})
38
Templating
▷ Templating engines are used to remove the cluttering of our server code with HTML,
concatenating strings wildly to existing HTML templates.
▷ EJS, Pug (formerly Jade) are some examples
▷ As we are using MERN stack we will be using React to create the frontend
39
Some useful npm packages*
1. Nodemon
2. Passport
3. Express-Session
4. Multer
5. Mongoose
nodemon does not require any additional changes to your code or method of development.
nodemon is a replacement wrapper for node. To use nodemon, replace the word node on the
command line when executing your script.
https://www.npmjs.com/package/nodemon
41
Passport
Passport is Express-compatible authentication middleware for Node.js.
Passport's sole purpose is to authenticate requests, which it does through an extensible set
of plugins known as strategies. Passport does not mount routes or assume any particular
database schema, which maximizes flexibility and allows application-level decisions to be
made by the developer. The API is simple: you provide Passport a request to authenticate,
and Passport provides hooks for controlling what occurs when authentication succeeds or
fails.
https://www.npmjs.com/package/passport
42
Express-Session
Create a session middleware with the given options.
https://www.npmjs.com/package/express-session
43
Multer
Multer is a node.js middleware for handling multipart/form-data, which is primarily used for
uploading files. It is written on top of busboy for maximum efficiency.
NOTE: Multer will not process any form which is not multipart (multipart/form-data).
https://www.npmjs.com/package/multer
44
Mongoose
Mongoose is a MongoDB object modeling tool designed to work in an asynchronous
environment. Mongoose supports both promises and callbacks.
https://www.npmjs.com/package/mongoose
45
Scaffolding
▷ Express application generator
○ quickly create an application skeleton.
▷ npx express-generator
▷ npm install
46
Scaffolding cont.
47
Scaffolding cont.
48
Express JS Examples
https://expressjs.com/en/starter/examples.html
49
Home Work
▷ Build something using Express JS
▷ Create a report/document
○ Functionality
○ Screenshots
○ Issues face
○ Github Repo Link etc.
▷ Upload it to VLE
▷ Not an assignment. Not mandatory.
50
References
https://www.tutorialspoint.com/expressjs/index.htm
51
Feedback
▷ Google Form - https://forms.gle/1Gk13Jzy47MwJ25N6
52
“
Thank You
53