MIDDLEWARE IN nodejs |nodejs tutorials

 

midleware before responding to actual request middleware responds 

in below middleware , we wil not pass params, it willl get automaticlly


const logger =(req,res,next)=>{}

const logger =()=>{

const method = req.method

const url = req.url

const time = new Date().getFullYear()

console.log(method,url,time)

next()

}


app.get('/'. logger, ()=>{})


app.get('/',logger, (req,res)=>{

res.send('HOME');

})


 




write that loggger in seperate page

logger.js

const logger = ()=>{}

module.exports = logger

import taht logger 

const logger = require('./logger');

use taht logger as middleware


app.get('/name',logger)
app.get('/name2',logger)

instead of using in all paths we can use app.use
app.use(logger)

app.get('/name')
app.get('/name2')

j

how to use multuiple middlewares

Authorize middleware

const authorize = (req,res,next) => 
{
console.log('authorize')
next()
}

impor this authorize middleare

app.use([authorize,logger])


get the id from name using authorize middleware



multiple middlwares for single api

app.get('/',[logger,authorize], (req,res)=>{

res.send('HOME');

})


morgan

npm i morgan

it logs for every http request 

require('morgan')

app.use(mogan('tiny'));



it brings from public folder

app.use(express.static(''./public));

 app.use(express.static(''./methods-public));

 if in this folder it has any  files taht wil reflect ist

like login page


previously we imported individual pages like script, css, index but now we use one folder directly 

so because of this it will will call after page loads

means login must for any page

get data into required file using api 


after click submit do axios post



https://github.com/john-smilga/node-express-course/blob/main/02-express-tutorial/methods-public/javascript.html

in request data there , if not there



























express json |node js tutorials

 


express.js

app.get
app.post
app.put
app.delete
app.all
app.use
app.listen

for any url it shows not found
app.all('*',(req,res)=>{res.status(404).send('<h1> resource not found</h1>')})




json basics

https://react-project-2-tours.netlify.app/

array of jsons


https://expressjs.com/en/5x/api.html

res.json([{}])


import json
const {products} =require('./data')
res.json(products)


const newProducts = products.map()
const newProducts = products.map(()=>{})
const newProducts = products.map((product)=>{
const {id,image,name} = product;
return {id,name,image}
})
res.json (newProducts)
it will filter the required keys

by product id


long lenth url




url
query=somethos&tags=comment






app.put






app.delete


router


api.js
 const route r = express.Router();
router.post
router.get

module.exports = router;

in app.js
const people = requoer('./routes/people')

app.use('api/people',people)


postman -api/people -> get


auth.js


 









http server |node js tutorials

how to write headers 

 const http= require('http');

const server = http.createServer()

const server = http.createServer(()=> {})

console.log(req.method);

req.url


const server = http.createServer((req,res)=> {

res.writeHead(200,{'content-type':'text/html'})

res.writeHead(404{'content-type':'text/html'})- page not found

res.end('<h1> home page</h1>')

})


server.listen(5000)



write fro html page

readfilesync= require('readFIleSync')

const homepage= readfilesync('./index.html')

res.end(homepage)

how to make navbar in html fully good ui

in navbar-app folder

it has styles.css, navbar.js,navbar.html







http messages |node jstutorials

 


https://course-api.com/

streams in nodejs | nodejs tutorials

 streams

writeable

readabvle

duplex 

transform

its like read and write

const {createReadStream} = require('fs');

const stream = createReadStream('./content/big.txt')

if file not there , it will create

stream.on('data', ()=>{})


stream.on('data', (result)=>{ console.log(result)})

after file create, read the data 


default buffer size is 64kb

const stream = createReadStream('./content/big.txt',{highwatermark:90000})

const stream = createReadStream('./content/big.txt',{encoding:'utf8'})

 






basic keywords or variables in nodejs |node js tutorials

 

globals

_dirname

_filename

require

module

process

 




any where u can access that varaivble is called global variables

in app.js

setInterval()
setinterval(()=>{},1000)
setinterval(()=>{
console.log('helloworld')},1000)

call back funciton is conole.log

to understand the code is easy - divide whole program into parts


write a function in es6
const sayHi =()=> {}
const sayHi = (name) => {
console.log('hello ${name}');
}
sayHi('susam');
const john ='hon';
sayHi(john)
fucntion sayHi(name)
{
console.log'hellow name');
}

every file in node is module
modules -encapsulated code ( only share minimum)

it will print that page
console.log(module);

local varoables and global varaiables
glaobl to uise in another module they are using export that required varaible

multiple exports


in impoer names.john, names.peter
if we  export any variable - it can cal it as global variable


require(modules locatioion)


single export
module.exports = sayHi

instant export

module.exports.items = ['item1','item2'];

const person = {
name :'bpb',
}

module.exports.singlePerson = person;


without export

output

input
7-mind-grenade.js



node js documentation - https://nodejs.org/dist/latest-v14.x/docs/api/http.html

i ssen in one lecture -
varaible declaration 
used in fucntion 
run this page
after taht 
varaible declaration in page
functin in one page
import in one page
run that page


use built in modules
info about current user



https://www.w3schools.com/nodejs/ref_modules.asp


current os type release totalmem



const path = require('path')

path module;
path.sep -> console .log

path.join('/content','subfolder','test.txt');
path.basename



















embedded javascript templates node js | nodejs tutorials

 create folder views

and index.ejs 


<!DOCTYPE html>
<html>
<head>
<title>TODO List</title>
</head>
<body>

<h2>TODOs List</h2>
<ol>
<% for( var i in tasks ) { %>
<li><input type="text" name="tasks[]" value="<%= tasks[ i ]; %>" /></li>
<% } %>
</ol>
<form action="" method="post"
onkeydown=" if( event.keyCode == 13 ) this.submit(); ">

<ol>
<% for( var i in tasks ) { %>
<li><input type="text" name="tasks[]" value="<%= tasks[ i ]; %>" /></li>
<% } %>
</ol>

</form>
</body>
</html>


in app.js

/ Use 'ejs' as the template engine
app.set( 'view engine', 'ejs' );

// Point unrouted requests to the 'views' directory
app.use( express.static( 'views' ) );
// Respond to any requests from the browsers..
app.all( '/', function( req, res ){
// Render index.ejs using a predefined list of tasks
res.render( 'index', {
tasks: [ 'Create Node.js App', 'Eat Dinner', '' ]
} );
});
var tasks = [ 'Create Node.js App', 'Eat Dinner' ];
app.all( '/tasks', function( req, res ){
// If the form was submitted..
if( req.body.tasks ) {

// ..use tasks from the form
tasks = req.body.tasks.filter( function( val ) { return val; } );

}
// Create an empty task
tasks.push( '' );
// Render 'index.ejs' using the up-to-date task list
res.render( 'index', {
tasks: tasks
} );
});
app.use(express.static('./public'));





complete nodejs project from scratch with rest api and mongodb| node js tutorials

 in this project u can ssee

how to create nodejs project from scratch

ist create folders like

controllers

database

models

node_modules

router

and files

personController.js in controllers

db.js in database

personSchema.js in models

personRouter.js in router

app.js

server.js

create anode initial fiel

npm init

then npm install express

server.js




const app = require("./app");
const PORT=3000;

app.listen(PORT,() =>
{
console.log("server on::"+PORT)
})


app.js

const express = require('express');
const app = express();


const personRoute = require("./router/personRouter");

require("./database/db");

let bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));




app.use(express.json());
app.use("/user", personRoute);

module.exports = app;


personRouter.js in router

const router = require("express").Router();
const personController = require("../controllers/personController");



router.get("/", personController.getAllPersons);



module.exports = router;


personSchema.js in models


var mongoose= require("mongoose");

const PERSON_SCHEMA = new mongoose.Schema(
{
fname:{type:String,require:true,unique:true},
lname:{type:String},
mno:{type:String},
addr:{type:String},
}
)

module.exports = mongoose.model("persons",PERSON_SCHEMA);


db.js in datgabase

var mongoose= require("mongoose");
const database=mongoose.connect('mongodb://localhost:27017/mydatabase' ,
{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then((res) => {
console.log(
'connected'
);
})
.catch((err) => {
console.log(
`not connected`,
err
);
});

module.exports = database;

personController.js in controllers

var person=require("../models/personSchema,js");


exports.getAllPersons = async(req, res) => {
try{
person.find({}, function(err,person)
{
if(err) throw err;
res.json(person);
})
}catch(err){
return res.status(400).send({error:"Unable to get persons", error: err})
}
}


run the app using npm start

then 

it will show get persons list









node js glimpse | nodejs tutorials

 Official NodeJS docs - https://nodejs.org/en/docs/


NodeJS download for windows - https://nodejs.org/en/download/

(simply click on downloaded file and it will install nodejs)


NodeJS for Ubuntu - https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-ubuntu-20-04

(it is best to use this process) - only use option 2, if you use option 1 (apt-get), it will install old version


NodeJS for mac - https://phoenixnap.com/kb/install-npm-mac

Install with homebrew


NVM installation for NodeJS - https://www.vultr.com/docs/install-nvm-and-node-js-on-ubuntu-20-04/


NVM for Mac - https://tecadmin.net/install-nvm-macos-with-homebrew/


NVM for windows - https://github.com/coreybutler/nvm-windows


NVM useful commands -


  1. `nvm  - -version` to check version 

  2. `nvm list` to list all the available nvm versions

  3. `nvm use 15.0` to use a specific version of nodejs

  4. `nvm install 15.0` to install a specific version of nodejs


Great books for NodeJS - 


  1. https://booksoncode.com/articles/best-node-and-express-books

  2. https://www.netguru.com/blog/node-js-books


Advanced Nodejs books - 

  1. https://amzn.to/3pgXveC

  2. https://amzn.to/3C4AeUZ

  3. https://amzn.to/3vZrcVh




Some great articles to learn NodeJS -


  1. https://medium.com/free-code-camp/what-exactly-is-node-js-ae36e97449f5

  2. https://medium.com/edge-coders/node-js-streams-everything-you-need-to-know-c9141306be93

  3. https://medium.com/dailyjs/how-i-automated-my-job-with-node-js-94bf4e423017

  4. https://medium.com/edge-coders/before-you-bury-yourself-in-packages-learn-the-node-js-runtime-itself-f9031fbd8b69

  5. https://yonigoldberg.medium.com/19-ways-to-become-a-better-node-js-developer-in-2019-ffd3a8fbfe38



Some great youtube videos for Nodejs -


  1. https://www.youtube.com/watch?v=TlB_eWDSMt4

  2. https://www.youtube.com/watch?v=ENrzD9HAZK4

  3. https://www.youtube.com/watch?v=sJ7nDNNpOMA

  4. https://www.youtube.com/watch?v=Oe421EPjeBE&t=14608s

  5. https://www.youtube.com/playlist?list=PL4cUxeGkcC9jsz4LDYc6kv3ymONOKxwBU


Some great projects to implement - 


  1. https://trevorlasn.medium.com/how-to-setup-a-powerful-api-with-nodejs-graphql-mongodb-hapi-and-swagger-e251ac189649

  2. https://medium.com/free-code-camp/securing-node-js-restful-apis-with-json-web-tokens-9f811a92bb52

  3. https://medium.com/free-code-camp/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2

  4. https://medium.com/codeburst/build-simple-medium-com-on-node-js-and-react-js-a278c5192f47?source=search_post---------12----------------------------

  5. https://medium.com/@atingenkay/creating-a-todo-app-with-node-js-express-8fa51f39b16f



Bootcamp - 


NodeJS starter kit [ Github ] -> https://github.com/AkhilSharma90/nodejs-starter


  1. Star it

  2. Clone it

  3. `npm install’

  4. `npm start` - will not work right now as don’t have an index file



NodeJS starter kit on Gitpod virtual environment -> 

https://gitpod.io#snapshot/964c6d65-bce5-4c05-a1a9-39712109c3b4 

(Note :- This is a gitpod - a virtual environment to run code. When you click on this link, the project will be copied to your gitpod account, so make sure you first create a gitpod account so you can access this later.)

Opening the project, you will see an error message, that’s because there is no server.js file right now. We will build it together.


========================================================================


COMPLETED PROJECT BELOW -


NodeJS CRUD APP [Github] -> https://github.com/AkhilSharma90/node-crud-project


NodeJS CRUD APP on Gitpod virtual environment -> 

https://gitpod.io#snapshot/8569488b-cb70-431c-9fc4-41b468d18f09 


POSTMAN Collection - https://documenter.getpostman.com/view/11345637/2s8YCbma7L


You have to run this in postman



Project board briefing - > https://whimsical.com/nodejs-masterclass-scaler-SJpzkrCwPj8tqWZLGNA7sj


======================================================================


EXTRA PROJECT, JUST FOR LEARNING PURPOSES - 


Github final ecommerce project ->

https://github.com/AkhilSharma90/node-ecommerce-V2/tree/master


javascript nuggets basics
https://www.youtube.com/watch?v=80KX6aD9R7M&list=PLnHJACx3NwAfRUcuKaYhZ6T5NRIpzgNGJ
https://www.johnsmilga.com/

https://github.com/john-smilga/VS-CODE-SETUP

https://github.com/john-smilga/node-express-course

Helpful Linux commands


  1. Stop server with port -> ctrl+c

  2. Stop server immediately, sometimes leaving the port open -> ctrl+z

  3. Kill processes on port - kill -9 $(lsof -t -i:8080)


Accessing a port on Gitpod - 3000-yourworkspace.ws-eu45.gitpod.io



node js is a mediator between server and html
node js is a javascript environment for developing applications that willl work in browser,server, terminal,desktop
popular javascript libraries and frameworks

jquery,angular,react

library is a collection of functions that extend the functionality of javascript
jquer,react,

framework is a collection of libraries that extend an applications environment
angularjs,backbone,js,ember.js

envirnorment is the server environment that executes the applications code
nodejs,python,ruby

nodejs is just a javascript
it allows javascript to be used for both froontend and backend

front end - client side
html, css, javascript

backend server side
java,php, ruby,nodejs


text editors
visual studio
atom
karkenjs.com

nodejs uses an eventdriven,non-blocking read

nodejs even in embeded sstem
node faster than php

node customers
linkedin,groupon,netflix,ebay,paypal

if compre with otherbackend
double the requests pers second
35% decrease in the avaerage response time

disadvantages

node js is not very strick languangue and lacks optimal data storage at this tume

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...