0% found this document useful (0 votes)
6 views26 pages

Nodejs Notes

The document provides an overview of Node.js, including its components such as the JavaScript runtime, event loop, and callback functions. It discusses asynchronous programming, file handling, and the use of Express for creating web servers and handling routes. Additionally, it covers package management with npm and the structure of modules and middleware in Node.js applications.

Uploaded by

bhagyesh2101p
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
6 views26 pages

Nodejs Notes

The document provides an overview of Node.js, including its components such as the JavaScript runtime, event loop, and callback functions. It discusses asynchronous programming, file handling, and the use of Express for creating web servers and handling routes. Additionally, it covers package management with npm and the structure of modules and middleware in Node.js applications.

Uploaded by

bhagyesh2101p
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
— x Node —> Seavey Request Web Server powt: ss00 Backend Scere port *4000 Deseever port | 3806 cor weapl Any kind of seer OX can seh Pore neo wali NY our wil’, pup port Nur bee 7 ce than 3500, gpotern Use that ports * Numbes 7 showd b& wis upto g3so° Jaya script <==} (wel | FRE Browse Favaseripit yo as eal g to run sme enritnment , Us farvascel pt ore Nodt —* Runt vuUddlLuUtLt PLELLELLUELELEEELELEGLELEEE > Meche ~7 Veasion | Developed b4 ° > node ASemolss Rayn Dan! 2°°9 Components of Node —> > TFavasewipt Runtime + V8 2> Enent loop S> Standort Component > Callback functions present in the fies as kept in queue & aftee | Kemet iG a a javascript Pile , theo cau pack functions ile 2xeudte - nat ae — catback functions oe excout t of emeution . . casters! pe Ss co single Ehresoke language the quer which holds cat back function = as call stack wee ee eae wihen carl earack '5 ele J > : cuted) sequen tially. eal) Stack queue rf crmeo) (ae & < 2% 48 a canned ay back functing ¢ nore : 5 rm — console log" Start '') ee Ssatimeout(() > a console log ti meous "| ) w gnside = x) - Promise swesolyc O): then ©) >t = console log(" onside promose" ) = é) = Bere oo. com ) 5 Micro T33k Queue cHighet ore cons: reg. | aie prod) 3 5 . 3» AP —* = CPna tole promise!) 5 End . noms macro Task Pueuw Claw ort console 109 al Vpnside timead!) bBU I e® posed OD. Seyrit cour 2 ty stac vr ask Quewrr o> mice a> Ma cro TASF Queue a> Animation Task QU " ~ Tt has sing! ere cal Co aad stack queue - ; _ Mic 0 Task DU ( Higher prioity ) oes Tous aa ( Lower priovity ) cau ba *€ High priow) ky bya Pu oF etion ail push in Micro Task Qu ue Q Lowee prion td y function will pul back : macro Task Queue Pe p ner teaser i * Fimstly au norma function all! Push Irrte Stack 2 execube pointe of * Onee cau stack is emptt, execurer goes to Micro task queus R Ue cau back function gers bo call stack execupe Tt . becomes ermpts % After execechion cau Stack of enecuter joe ZoOemaCu! again, pointe sy Pp al cout bach function gers a Task queuw & cau stack Rg execute Pr 4K “TO perform asynchronovgs this method Game into % File Import] Export —> ee programming exishtan ce © mMaeh ss ~ module. exports =4 add, Sub, mul } @ Aemojs 2 meade const math = requre(! +/met h!') console log (éypeof( math) ) // © bj ect console:log CmMath) // add ,sub Mu math: ada Clo,20 ) moth: Sub (2055 ) math: Mu (2°,7 ) -TP we want +o change the pro pete name j- 2 function name while exporting ~~ ~ module -expotts = d add , sub, Multiplication : youl | while accessing —~— math -Multiplicxtion (20,7 ) than es POMOM Mer ' OPE f Of fF HHO € ~~ GC) Mathys 4 modu. exports = add @ emo js : const Marh = require ( h/moth') = console log C Eypeot cmotn)) JI funehon console logC moth) Jf add matrh( 10,20) moths mons: Gee oe module © XPOTHS =p ademas / const math = yequireC* mad h') 11 Number Cmeth ) > conse! ctype /7 BlHe console 19g math) it oO marhjs ‘nh Lexports= ado mmeaule: popes =4eum si * i * > ' encit chsh Sy aed au ou Sa josh z = Jodie: exports 5uUb = sub modwe- exports= ada B® seme ; ide : . eae Of cob 15 ONEAAS [ funet on sada _) Beto punerion —_ Node Favascoipt THPrt -PKPOP ES | DBA MAPEM|S gy efault adol ——=) @® emo y a =a 4s) mp ro dee favescaipe his SYNTAK js used FO import mdth For \yrmak heemys L ES | export default add ovt sdb pert er v. pmath & mjs import {suby From \.ppneth s+} S/ rot b C19, 297 Vy addition gub (2219) fy) subteaction Tt Laub , maltipricaFion os mw [ne mu(7 lt) 3 Pam * /rnabh ras pbbb GCEUGUssy Toeinewerrnnryy? ‘ BOUUE [ [ [ = [ wud “ 4 vba * BuleTy Modules —> Ib const os = Tequhre C08") (impart) console log (typeof cos) ) Sf Obj ect console (ogC os) propeseses console log Cos plarfor 9 (1 Winsr console jog Cos veEsion ) console log9 (os: hasenam £< >) Ss console jog CO arch©)) wire ( ‘FS! > yy object 2> nacre -109C EYES CF S?? Pi Funceiors which doesn't have in Name'syne Wea asynehro nos + hot ae punckions eg: waite FileSyn write — ASsyne © weiting funchiod eorriteintorty Eile Gad oto 7 console leg laSyne (imydata exe! eS peo" ) em SYN Chron Us herons Ss writer 5 console- 109 c computed") crert egntotty Fie Y) lp Gis eee console: ogc" Mon) oor his © Reading GC syne) _— popstigte Teg eta const datas PS pead prle Sy Ne C mvdacta txt") console (09 Cdata ) consalt jog (apie read compthal \ ) b 7 erie Toad etotte) seead MYPIEU) olp> FF console leg (%one") ' File Tead comp |lebu Done- t ® Reading ( async ) Reding © as7ne co nat datez Pg mread hile Curmyeete txt", PSE, ( etto* > dota) > < console og¢ data ) a) ~~ eh cat ej Hat sie ~ oO)p— a idyel fPunction’s atl last @1 wead File exe ade fo , working oF Nodelt | v F ne CD i part modue htte const http = wequireT http’ ) esves oO Ryeot Using ereate$rreO functio# DU storing $ Srereoneh tte: creas eer Ccreq, bes I> 0gl" Consclaingg hipete © Oeste 2 &) hoa cveeted use method listn age Ss staat the seer Bee listo < ‘pocathast » ©) a4 sfog (" SU 3) ooo, goles is stashed at pot 44000") co - ; OD conse Seer = httP: aqeate Sere (F4, a) > const method = req De hod const url = req -uvl if Curl == ‘vase! MRmethod <= GET!) X gos end (OS® data ') poskue} ait | f ae vp Cutl 2=" \pood ual!) § ‘| A mpeg end (tprodueh alapat ) _ ene { sesend ©" Ente cotzeh APL" ) Yr ~~ 1> Postman —> create workspace : Por jl al i a R alse for testing pices 27 ow cathe collection Workspace - collection = fololer — wequede E + Bydefout (chrome) prowsee surrorts PY . (GET? method, so to test other mebbods [fee POST, PUT, DELETE we use Postman iy 0% - we 1 http backend seenee 4e Routes — -ftiso way +0 communicat® a end Sceneke- - o decide jth the beck wot tty yb as € eedks to be what task 0 ud > > - Tt haps + , , pee form ed pov the IN coming req , = ute 20 be confi eee) iD) joben tit ge : ree merhod Q the path Geom incoming PA h method - GET podh-/usH * gt oe gens from db Method - post pobp-/use : add wee to db mothed — PUT poth- /use . Update use in the db method — DELETE path - Jus 3 Auphe blew from db . \ +4 > GET Ju se] 9 pep mean Ts Pres —> post fusee/signin — post | ireoavsel ~, pUT sileftd — GET Jus®/pren eft , eresvet « ouiete yuse/y > bere Juse-/t - PUT Ww Content-type —7 ves. sepHteaden (‘content= #9 p© 1 'text/ plan'} / _ 1 \ eur! pres eehhi endsy CLCOD rene topes serpy ; res sepHeooker( Voontent -tg P© /, Sapplication/ 50” ) X Write conteint int? pespor se first & ED end wes: write ( ros wvite Cc wes .endl) Veh Halo '?) choy vse cher) coRs = C8OSS origin Res owe shal policd ag alow REFUSE Prom UW ongin — apes: SG Heooke Ci Access -contrel- Allow Origin’, '#!) ¢ Preflite Request —> Featwy of Browser (Desttp) * Express —> ~ > Package Managet —> NPM _npm - Pe Node Package manager ) 2? package mana + yarn > opm init : package name yession [:0°0 fing ebockend sere package ;jso desesiption testing epee express entry point! seevee SS ; express jnstalad? ++ >n\erm jostat! express dependencies pdded rnpm \nsteu Cit we added 99 use this command to upd ate in pactege 5°? file ) semen JS 2 = requre crexpress') const expres> = express () const @PP = sere thaten (4008 O68) NOTE 2 O>< console 89 (1 ger whortted) at port 4000") A) > node ceere ss G1 cy file) r * Route — ap, pega Us, Cveg, 75) > fone oe jog (1 E xpress backend cables") Ss. send (Hello from empress seduces” ) 5 é) & Node Monitor nodemon yt is a tool to monito® the o nod@ eekvek * changes >npm install local yp otal lobio n > oem instoll-3 -globat ipstalotlo? instal globollg Nodelmon sfrowtd be >npem instal) ~5 nodeme > nodemed —-yeesion ( Restart ve code ) > nodeMmon seer 'JS ade HEY Roel Yee SOAR @! prey ey OYE COME “HS 021i | 6 mon atim) Ble, @tiue) Yat ohm «Te 30,0 4 aiayetly changes monite x09 240.0) upd ate bin + Nodemon Ldal AI SO oy, changes xl, ape Bulan changes pofject One . Route — > appget Cruse’, (red 4) a4 eos send (S User dara gt") oy t) yes gend (Uses ) = p27 app: get ('/produ r oct |) Cre, Te3) DS 4 = const body = % Status , Neueces ” data . products ‘ é) ves “gend ¢ bod 4) 4 a express with Database — @rasee 2, COPIF CD BOX Insta! 7" pnpm ceave JS 4 expTess = wequ = requrel }: create Poo! ( & mysql cons rec express!) > const my 2al tmysq2') 2 Mmys4 conse poo! \focethos t's host : use: \a@oot! » password : Vpoot ’ , dopabose : ola c-olb' i) cons opp ot C const ool queey C39!) J) console: 19g (data ) /Jeconsde log (eezot ) yess OC) veg bes dD =>4 \ geloct ¥ Prom use” (esto, data) >4 c app = OP yuseet & l= CCST = if Coat) « pas-sond ( 4 gtethss Noyccees” SEE dals)) p OS yes cope (4 Stabay »“oetow”, Cb4oe ) 7 YF APT —= ( pPpplication programm http -/slocal host * http // Joced host 14500 ptegin over \ VA —_" Modwarity —> > Make dire ctory calle) oF \ poutes ” QR Make alee woutes separatel category & 9° user JS, a (CEBERS Router —> 1S Used £o Crecde 7 uti ple ln modulo “449 => 9+ is also cal »> usetys const express = a exp Tess ~ Usedto add multip! require’ express ) nr anteetace ) 55 co/lagin htm! jy aocovd ing t? ordiej Ss, produch:js wouteds 2d AS MiNi expTAss ap phot PrrInonn » 2 1 HhoePronnApAoAnnnowgA J ‘ ow Dh oo st on F 1 q Hy Od Sees const expy . Pipa hin < | SEGRE S etl recmags opp=express() ew) J/ Middl jeDake —> Tt is function Fhoy 2xecutos _ Foe eveby Single incoming TeJUest _5 design in o way that aecept a fun ction & this tion is cast back function . fune app usecc Ted, TES, NeXt) IK a console-log (iM fadyinare CAMd 1) | urobetto in next ©) ty n code akh equine foe at Tous te // comm ' pvitten in Midd bate ) rothod Hed (tong we he > pp we ae Uding USE uy USING mide) edate» por path= /produst fatima (uses Rout et ) useeRouter “a <= ne cheek tat : Ado a -Use producRoute® ) de perce) will [oop vse (prone eoure) ¢ PVC OM prod ud Row weg check SO, b 2 1 ody ~ ductRouke 44 tor pat : cheoktto Ath PTS are gen Route AE check SXO. eit) e1USO aiyac are Uo ,f Id oveeheod ae area) gol” we — gpecific Toure dep check 2K. 2) ~ ADD dX WK USO . cess potas) 2 gem / YU See Gut, poudas ac petpn loce host 4000/8 For sees for usedys Aga) JUN, wa sol? HS a ; elt Stiue) woutes Hoty Acc wwoutes ge (V7! COI, ves) > % ~wes-send (" Useergdt from ssoudee") 4) Bet) Access W 4 [Link](“ “) £) mwoutes post (* /* wpe gond C* 1) crey eID &) eh fp second pash cath OFO , Har @ xp 1hO# 4 yours add ae path Glldl.. M, wouber past (signup /k 827,72) > ¢ parcod(™ &) pouseL” post ( psisnin', (9,82 4% A rd we CURD operation — eS 5 \Py qi> source path of mysaqipile sq! ‘] Ansteed of copy | past do this —? epyew) Must be in data from client to S lp woke to do this json format so add rida U/_ midd wear app -US© (express json? ) // Routes outers postC's', (veg ves) > 4 4 oe const body= wr eq: body email, Pass req body 3 je [const Aname, a7 mobile, C1 = st \neeete inte useeg (name, email , const $7! = mobi; ‘city ) Vad ues {email $1, Bx passaord?’, bf password Fi G{name $6 ‘gq citi 7’) pool query ( $4) if ( daka JX “628 Seno) ( dat Sata ) mobile yy , Cazboe, Sate ) 2< —— s seg end ( e204 ) A) p ey Roukes g F routes put Crt, (req, res) > 4 Dome SSD const 4 uid , Mobile, cjty A = wveq» body yh O ss const sql- ‘update usess set mobile = » simebile } 5 city 2! gs city / fo. whee wd = £ {uid > zs pool: query (sq, Cessow, dota)? 4 it (daha) PMA , pes-gend (data) oa “ses cond Cdavot ) £0) ey ia routes: delete (ssp id ’, Crveq, ves) 2 ¢ - URL const wd = req: params-id KEP, DPHNANDNN AP MANA const 34] = 'Delde from usu hwo wd = thuidt % a 1) pool-quety ( sql, Cettoe, Hota ) >4 ip Cdara) — ves send Coata) DTNDD OMT eu. send (esoe ) &) pexomsid diva noo 1, Power “ep . yours deeb (\/rid, (reg, ve) Dx ‘ n to po se defined Module — my Mape new directory cal od ‘utils / =p obs = monst Mysql = srequire (1M sq! 2!) const pool = amysq hs Createped \ & £ modus exesrts = 25] ———— ' ~ Teo a requive GTustis/ 4b") ° const peo = 2> re swt JS Function create fest const resuh 24 + it (dota) 4 peswt [istatus! J = Usuecess’ pest dara’) = (eso, data ) 5 , S dora 2 emot” Fas ¢ apeswit Crstabus ‘J mpeg AFL? eesor "J = COD ‘ aU) peswt + Oe oD be dd Teno dusecegpars = eam TS ¢ wou JS . . . a wos es vogult = pequire C we pupris[weswt) + » * econ gusty (sq, ( ersot alata) 4 4 ares send (PauUt: Crvake Rast} ( e2tot dota ) : v r > ORD install express My4S41 Buy uol alod , Signdn/ SignUp > To utes. pos t (Yregistee' ¢ way \4koltr$ y? pool quergC sd! Cero, data) =>4 1? cdota? oes ageincend (Aes ) else wes seend C e204) &) &) a ee wea utes post C/129'0 , Cre9, res > 4 4 email, password > 2 weg: bodd \ geluet x From Users ahi emal = 2 'g ¢passaordé' * const const sql= , Secemailé AND password pool gq usty (sat, eeeot. 1 a49 dad nae, eh C dara |= wpessehd (ata) ee : : . rh not send Co ghahs Neppot!” eshoz ' wpnyalid email" &) §) &) ‘$4 email f’ \$ {pass Dord b' vg kemsbilh a s Dane? Pein n p LEUPrnnoonms >) f) sh cn on QI Om Freee we SOL Pn fection —> - password 2 Sppuk tor” _ ap we wse etring con fatinabio? hackes can use sel injection [ree abort & can hook gata » This is Why String concedination ks nok Used + _ This eyp~ Of queries CaN CO hence unsefe to Use » : _ gnstead of waiting Wwe asing GtTr concadinat oy used repose cohatermends ens Whew use 39! Pn j eatin k * \celectt * fearom us const eql= \ ~ ~ 3 a AND pass word= ? email> ? ( eatoe, data }» ,cemal, pool: query (34! password J , if (dara ** df ares send) ( {stony ! sgucctds” | dato § ) ese 4 ee ee eee ertod.! - uppralid uaterane ov pap ood't) i) pee We Use 2 19 query g provide abday in pool Guy . c emai, pete : : fivst quastipn ae roqrek CUbLbEbbELE > > 9 ro i x Password Hashing ( Encryption) —> i t % Password Hashing —> = Hashing agorithm = Bowy pt » COPS, - even 'f pass word be different —> bevypt J hash yaue ©? .C 1es% gets) ay — deweloped b+ acousity engineer a — besypt , cwypte Ts C Alege ith ms 7 al > 9PM instal berypt os js game hosh value CAD ~ | (more secukr ) n be - Por same passwort > cr ptots same mma const bcry x reequive (bet IP®’) conse sur ous =19 Sothern pose Ci) regisie 4 OPS Coreg PAI =3fe conse {name pessword , mobil city} = email, 2 » = Teq: bods ; Ee f Sinseet inbo Uses (name, cima, - 1 | i 1 =) 1 i 1 | Sy const sqlz password , mobile city) varus (2,252.2, S passworel = awayt b crypt hesh < password , Sal ROU hos hpassword al te) 4 const hash T pool query (541, LPAM® 5erMalls mobile, Je, Ceeot, data) < " S# Colata 4 708 SHI (Xstebus wnsucced", dake £ ) Cees send (status Seaboe", ertot f ) cote centr | aonol C{ shore eesod? ertor d ) = Decvryptrons —>» route post C/login’, (wed, Te3) => < c , onst {emajl, password fF = weq: body oonst sq(z\ select « from UY hake erica =n a aE pool quake (eq), Lemall 1, 2206 se C data ee dA eonst US = ( extort Jahiyt daba COI bewypt compe cont Teswt = (pass2ord, wu searpassie) ap (west ) 4 wg reuccess |, JAF y 4 send (Keteh ore. b alee vognoe” Ze 4 weg send (4 ote’ | nee é wepnvatid uname 0° Po "* ) : UE 1 ston! 0L40% 3 eaten Cones? 4 aces send CK habad NO, | , / » gowabhing vent LIPO &) 5 \% \o8 : Sw WEEE Cpe > YAR bare se TWT —s FSON Web token ~used for aubhovlxction Token—~ ay [oa heoder- , secret >nem jostat yoonweb EOF ep const payload =f ld + AbOsem: who} sree of + pb const +okeD = qe Sign (patlood, config -secved ) oan a a For every request send by Usb » WY News o token . only Tegisten & login can allowed witha token. beac +hot poethod” cmeodg +ohen app: vse (C req, Tet, NUKE ID < 6 const allowed Ris = Liyusee/tegiste » Yuserflesif= const url = veqeuvl if Cat! owed URLs inclushs cubi jd U8 (gp the ual & tor register O€ login we Gon} Noa! bo Cheb teh” < next) e)se , URL ISfow Tapishy X login wentel to © rt porous & lyn = i we Mure poulter ie a pack to upload any = kind of pile erg Pat, img, PPG, JPG > >nPm ingtau mur. => nat rulers TEPAye Cirmutee) const Coase _ muper (4 dae: ‘mages /" b) upload proper post QG7', uploaal singlef rcouset neg) , Cgeq res) 4 const Aname , discription, “deag } = 8H LOY cong { origina Nam 1 Parh § = OG. ile wudceeus Vimages/! +- Ovi ginetname , ¢ e220 ) >4+) dasevip ti , fees, fs: venamel path , CONst Sq! =| Angesp into co usses (N22 » image ) varus (2,212 2 *& fetching image Py) Nidal erra%s 1 app use CLiMBE, aL pp [covrees | imagefslon PY express stotic (iiroages J) 5 oo postman —> 440 f) 1» D

You might also like