Post on 11-Sep-2021
LearnNodeJSin1Day
ByKrishnaRungta
Copyright2016-AllRightsReserved–KrishnaRungta
ALLRIGHTSRESERVED.Nopartofthispublicationmaybereproducedortransmittedinanyformwhatsoever,electronic,ormechanical,includingphotocopying,recording,orbyanyinformationalstorageorretrievalsystemwithoutexpresswritten,datedandsignedpermissionfromtheauthor.
TableOfContent
Chapter1:Introduction
1. Whatisnode.js2. WhyuseNode.js3. FeaturesofNode.js4. WhentouseandnotuseNode.js
Chapter2:Download&InstallNode.js
1. Howtoinstallnode.js2. Installingnodethroughapackagemanager3. RunningyourfirstHelloworldapplicationinNode.js
Chapter3:Modules
1. WhataremodulesinNode.js2. UsingmodulesinNode.js3. CreatingNPMmodules4. Extendingmodules5. PublishingNPMModules6. Managingthirdpartypackageswithnpm7. Whatisthepackage.jsonfile
Chapter4:CreateServerandGetData
Chapter5:Node.jswithExpress
1. WhatisExpress.js2. InstallingandusingExpress3. WhatareRoutes4. SampleWebserverusingexpress.js
Chapter6:Node.jswithMongoDB
1. Node.jsandNoSQLDatabases2. UsingMongoDBandNode.js3. HowtobuildanodeexpressappwithMongoDBtostoreandservecontent
Chapter7:Promise,Generator,EventandFilestream
1. Whatarepromises
2. Callbackstopromises3. GeneratingpromiseswiththeBlueBirdlibrary4. Creatingacustompromise5. Callbacksvsgenerators6. FilestreaminNode.js7. EmittingEvents
Chapter8:TestingwithJasmine
1. OverviewofJasminefortestingNode.jsapplications2. HowtouseJasminetotestNode.jsapplications
Chapter1:Introduction
Themodernwebapplicationhasreallycomealongwayovertheyearswiththeintroductionofmanypopularframeworkssuchasbootstrap,AngularJS,etc.AlloftheseframeworksarebasedonthepopularJavaScriptframework.
Butwhenitcametodevelopingserverbasedapplicationstherewasjustkindofavoid,andthisiswhereNode.jscameintothepicture.
Node.jsisalsobasedontheJavaScriptframework,butitisusedfordevelopingserver-basedapplications.Whilegoingthroughtheentiretutorial,wewilllookintoNode.jsindetailandhowwecanuseittodevelopserverbasedapplications.
Whatisnode.jsNode.jsisanopen-source,cross-platformruntimeenvironmentusedfordevelopmentofserver-sidewebapplications.Node.jsapplicationsarewritteninJavaScriptandcanberunonawidevarietyofoperatingsystems.
Node.jsisbasedonanevent-drivenarchitectureandanon-blockingInput/OutputAPIthatisdesignedtooptimizeanapplication'sthroughputandscalabilityforreal-timewebapplications.
Overalongperiodoftime,theframeworkavailableforwebdevelopmentwereallbasedonastatelessmodel.Astatelessmodeliswherethedatageneratedinonesession(suchasinformationaboutusersettingsandeventsthatoccurred)isnotmaintainedforusageinthenextsessionwiththatuser.
Alotofworkhadtobedonetomaintainthesessioninformationbetweenrequestsforauser.ButwithNode.jsthereisfinallyawayforwebapplicationstohaveareal-time,two-wayconnections,whereboththeclientandservercaninitiatecommunication,allowingthemtoexchangedatafreely.
WhyuseNode.jsWewillhavealookintotherealworthofNode.jsinthecomingchapters,butwhatisitthatmakesthisframeworksofamous.Overtheyears,mostoftheapplicationswerebasedonastatelessrequest-responseframework.Inthesesortofapplications,itisuptothedevelopertoensuretherightcodewasputinplacetoensurethestateofwebsessionwasmaintainedwhiletheuserwasworkingwiththesystem.
ButwithNode.jswebapplications,youcannowworkinreal-timeandhavea2-waycommunication.Thestateismaintained,andtheeithertheclientorservercanstartthecommunication.
FeaturesofNode.jsLet'slookatsomeofthekeyfeaturesofNode.js
1. AsynchronouseventdrivenIOhelpsconcurrentrequesthandling–ThisisprobablythebiggestsellingpointsofNode.js.ThisfeaturebasicallymeansthatifarequestisreceivedbyNodeforsomeInput/Outputoperation,itwillexecutetheoperationinthebackgroundandcontinuewithprocessingotherrequests.
Thisisquitedifferentfromotherprogramminglanguages.Asimpleexampleofthisisgiveninthecodebelow
varfs=require('fs');
fs.readFile("Sample.txt",function(error,data)
{
console.log("ReadingDatacompleted");
});
TheabovecodesnippetlooksatreadingafilecalledSample.txt.Inotherprogramminglanguages,thenextlineofprocessingwouldonlyhappenoncetheentirefileisread.ButinthecaseofNode.jstheimportantfractionofcodetonoticeisthedeclarationofthefunction('function(error,data)').Thisisknownasacallbackfunction.Sowhathappenshereisthatthefilereadingoperationwillstartinthebackground.Andotherprocessingcanhappensimultaneouslywhilethefileisbeingread.Oncethefilereadoperationiscompleted,thisanonymousfunctionwillbecalledandthetext"ReadingDatacompleted"willbewrittentotheconsolelog.
2. NodeusestheV8JavaScriptRuntimeengine,theonewhichisusedbyGoogleChrome.NodehasawrapperovertheJavaScriptenginewhichmakestheruntimeenginemuchfasterandhenceprocessingofrequestswithinNodealsobecomefaster.
3. Handlingofconcurrentrequests–AnotherkeyfunctionalityofNodeistheabilitytohandleconcurrentconnectionswithaveryminimaloverheadonasingleprocess.
4. TheNode.jslibraryusedJavaScript–ThisisanotherimportantaspectofdevelopmentinNode.js.Amajorpartofthedevelopmentcommunityarealreadywellversedinjavascript,andhence,developmentinNode.jsbecomeseasierforadeveloperwhoknowsjavascript.
5. ThereareanActiveandvibrantcommunityfortheNode.jsframework.Becauseoftheactivecommunity,therearealwayskeysupdatesmadeavailabletotheframework.Thishelpstokeeptheframeworkalwaysup-to-datewiththelatesttrendsinwebdevelopment.
WhousesNode.js
Node.jsisusedbyavarietyoflargecompanies.Belowisalistofafewofthem.
Paypal–AlotofsiteswithinPaypalhavealsostartedthetransitionontoNode.js.LinkedIn-LinkedInisusingNode.jstopowertheirMobileServers,whichpowerstheiPhone,Android,andMobileWebproducts.MozillahasimplementedNode.jstosupportbrowserAPIswhichhashalfabillioninstalls.EbayhoststheirHTTPAPIserviceinNode.js
WhentouseandnotuseNode.jsNode.jsisbestforusageinstreamingorevent-basedreal-timeapplicationslike
1. Chatapplications2. Gameservers–Fastandhigh-performanceserversthatneedtoprocessesthousandsof
requestsatatime,thenthisisanidealframework.3. Goodforcollaborativeenvironment–Thisisgoodforenvironmentswhichmanage
document.Indocumentmanagementenvironmentyouwillhavemultiplepeoplewhoposttheirdocumentsanddoconstantchangesbycheckingoutandcheckingindocuments.SoNode.jsisgoodfortheseenvironmentsbecausetheeventloopinNode.jscanbetriggeredwheneverdocumentsarechangedinadocumentmanagedenvironment.
4. Advertisementservers–AgainhereyoucouldhavethousandsofrequesttopulladvertisementsfromthecentralserverandNode.jscanbeanidealframeworktohandlethis.
5. Streamingservers–AnotheridealscenariotouseNodeisformultimediastreamingserverswhereinclientshaverequest'stopulldifferentmultimediacontentsfromthisserver.
Node.jsisgoodwhenyouneedhighlevelsofconcurrencybutlessamountofdedicatedCPUtime.
Bestofall,sinceNode.jsisbuiltonjavascript,it'sbestsuitedwhenyoubuildclient-sideapplicationswhicharebasedonthesamejavascriptframework.
WhentonotuseNode.js
Node.jscanbeusedforalotofapplicationswithvariouspurpose,theonlyscenariowhereitshouldnotbeusedisiftherearelongprocessingtimeswhichisrequiredbytheapplication.
Nodeisstructuredtobesinglethreaded.Ifanyapplicationisrequiredtocarryoutsomelongrunningcalculationsinthebackground.Soiftheserverisdoingsomecalculation,itwon'tbeabletoprocessanyotherrequests.Asdiscussedabove,Node.jsisbestwhenprocessingneedslessdedicatedCPUtime.
Chapter2:Download&InstallNode.js
TostartbuildingyourNode.jsapplications,thefirststepistheinstallationofthenode.jsframework.TheNode.jsframeworkisavailableforavarietyofoperatingsystemsrightfromWindowstoUbuntuandOSX.OncetheNode.jsframeworkisinstalledyoucanstartbuildingyourfirstNode.jsapplications.
Node.jsalsohastheabilitytoembeddedexternalfunctionalityorextendedfunctionalitybymakinguseofcustommodules.Thesemoduleshavetobeinstalledseparately.AnexampleofamoduleistheMongoDBmodulewhichallowsyoutoworkwithMongoDBdatabasesfromyourNode.jsapplication.
Howtoinstallnode.jsThefirststepsinusingNode.jsistheinstallationoftheNode.jslibrariesontheclientsystem.ToperformtheinstallationofNode.js,performthebelowsteps;
Step1)Gotothesitehttps://nodejs.org/en/download/anddownloadthenecessarybinaryfiles.Inourexample,wearegoingtothedownloadthe32-bitsetupfilesforNode.js.
Step2)Doubleclickonthedownloaded.msifiletostarttheinstallation.ClicktheRunbuttoninthefirstscreentobegintheinstallation.
Step3)Inthenextscreen,clickthe"Next"buttontocontinuewiththeinstallation
Step4)InthenextscreenAcceptthelicenseagreementandclickontheNextbutton.
Step5)Inthenextscreen,choosethelocationwhereNode.jsneedstobeinstalledandthenclickontheNextbutton.
1. FirstenterthefilelocationfortheinstallationofNode.js.ThisiswherethefilesforNode.jswillbestoredaftertheinstallation.
2. ClickontheNextbuttontoproceedaheadwiththeinstallation.
Step6)Acceptthedefaultcomponentsandclickonthenextbutton.
Step7)Inthenextscreen,clicktheInstallbuttontostarttheinstallation.
Step8)ClicktheFinishbuttontocompletetheinstallation.
InstallingnodethroughapackagemanagerTheotherwaytoinstallNode.jsonanyclientmachineistousea"packagemanager".
Onwindows,thenodepackagemanagerisknownasChocolatey.Itwasdesignedtobeadecentralizedframeworkforquicklyinstallingapplicationsandtoolsthatyouneed.
ToinstallNode.jsviaChocolatey,thefollowingstepsneedtobeperformed.
Step1)InstallingChocolatey–TheChocolateywebsite(https://chocolatey.org/)hasveryclearinstructionsonhowthisframeworkneedstobeinstalled.
Thefirststepsistorunthebelowcommandinthecommandpromptwindows.ThiscommandistakenfromtheChocolateywebsiteandisthestandardcommandforinstallingNode.jsviaChocolatey.ThebelowcommandisaPowerShellcommandwhichcallstheremotePowerShellscriptontheChocolateywebsite.ThiscommandneedstoberuninaPowerShellcommandwindow.ThisPowerShellscriptdoesallthenecessaryworkofdownloadingtherequiredcomponentsandinstallingthemaccordingly.
@powershell-NoProfile-ExecutionPolicyBypass-Command"iex((new-objectwet.webclient).DownloadString('https://chocolatey.org/install.ps1'))"&&SETPATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin
Step2)ThenextstepistoinstallNode.jstoyourlocalmachineusingtheChocolatey,packagemanager.Thiscanbedonebyrunningthebelowcommandinthecommandprompt.
cinstnodejsinstall
Iftheinstallationissuccessful,youwillgetthemessageofthesuccessfulinstallationofNode.js.
Note:Ifyougetanerrorlike“C:\ProgramData\chocolatey\lib\libreoffice\tools\chocolateyInstall.ps1”Thenmanuallycleatethefolderinthepath
RunningyourfirstHelloworldapplicationinNode.jsOnceyouhavedownloadedandinstalledNode.jsonyourcomputer,letstrytodisplay"HelloWorld"inawebbrowser.
CreatefileNode.jswithfilenamefirstprogram.js
varhttp=require('http');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.end('HelloWorld!');
}).listen(8080);
CodeExplanation:
1.Thebasicfunctionalityofthe"require"functionisthatitreadsaJavaScriptfile,executesthefile,andthenproceedstoreturnanobject.Usingthisobject,onecanthenusethevariousfunctionalitiesavailableinthemodulecalledbytherequirefunction.Soinourcase,sincewewanttousethefunctionalityofhttpandweareusingtherequire(http)command.
2.Inthis2ndlineofcode,wearecreatingaserverapplicationwhichisbasedonasimplefunction.Thisfunctioniscalled,wheneverarequestismadetoourserverapplication.
3.Whenarequestisreceived,weareaskingourfunctiontoreturna"HelloWorld"responsetotheclient.ThewriteHeadfunctionisusedtosendheaderdatatotheclientandwhiletheendfunctionwillclosetheconnectiontotheclient.
4.Wearethenusingthe.listenfunctiontomakeourserverapplicationlistentoclientrequestsonportno8080.Youcanspecifyanyavailableportoverhere.
ExecutingthecodeStep1)Savethefileonyourcomputer:C:\Users\YourName\firstprogram.js
Step2)Inthecommandprompt,navigatetothefolderwherethefikeisstored.Enterthecommand
Nodefirstprogram.js
Step3)Now,yourcomputerworksasaserver!Ifanyonetriestoaccessyourcomputeronport8080,theywillgeta"HelloWorld!"messageinreturn!
Step4)Startyourinternetbrowser,andtypeintheaddress:http://localhost:8080
OutPut
Summary
WehaveseentheinstallationofNode.jsviathemsiinstallationmodulewhichisavailableontheNode.jswebsite.ThisinstallationinstallsthenecessarymoduleswhicharerequiredtorunaNode.jsapplicationontheclient.Node.jscanalsobeinstalledviaapackagemanager.ThepackagemanagerforwindowsisknownasChocolatey.Byrunningsomesimplecommandsinthecommandprompt,theChocolateypackagemanagerautomaticallydownloadsthenecessaryfilesandtheninstallsthemontheclientmachine.AsimpleNode.jsapplicationconsistsofcreatingaserverwhichlistensonaparticularport.Whenarequestcomestotheserver,theclientautomaticallysendsa'HelloWorld'responsetotheclient.
Chapter3:Modules
AmoduleinNode.jsisalogicalencapsulationofcodeinasingleunit.It'salwaysagoodprogrammingpracticetoalwayssegregatecodeinsuchawaythatmakesitmoremanageableandmaintainableforfuturepurposes.That'swheremodulesinNode.jscomesinaction.
Sinceeachmoduleisanindependententitywithitsownencapsulatedfunctionality,itcanbemanagedasaseparateunitofwork.
Duringthistutorial,wewillseehowwecanmakeuseofmodulesinNode.js.
WhataremodulesinNode.js?Asstatedearlier,modulesinNodejsareawayofencapsulatingcodeinaseparatelogicalunit.TherearemanyreadymademodulesavailableinthemarketwhichcanbeusedwithinNodejs.
BelowaresomeofthepopularmoduleswhichareusedinaNodejsapplication
1. Expressframework–ExpressisaminimalandflexibleNodejswebapplicationframeworkthatprovidesarobustsetoffeaturesforthewebandmobileapplications.
2. Socket.io-Socket.IOenablesreal-timebidirectionalevent-basedcommunication.Thismoduleisgoodforcreationofchattingbasedapplications.
3. Jade-Jadeisahigh-performancetemplateengineandimplementedwithJavaScriptfornodeandbrowsers.
4.MongoDB-TheMongoDBNode.jsdriveristheofficiallysupportednode.jsdriverforMongoDB.
5. Restify-restifyisalightweightframework,similartoexpressforbuildingRESTAPIs6. Bluebird-Bluebirdisafullyfeaturedpromiselibrarywithfocusoninnovativefeatures
andperformance
UsingmodulesinNode.jsInordertousemodulesinaNode.jsapplication,theyfirstneedtobeinstalledusingtheNodepackagemanager.
Thebelowcommandlineshowshowamodule"express"canbeinstalled.
npminstallexpress
Theabovecommandwilldownloadthenecessaryfileswhichcontainthe"expressmodules"andtakecareoftheinstallationaswellOncethemodulehasbeeninstalled,inordertouseamoduleinaNode.jsapplicationyouneedtousethe'require'keyword.ThiskeywordisawaythatNode.jsusestoincorporatethefunctionalityofamoduleinanapplication.
Let'slookatanexamplehowwecanusethe"require"keyword.Thebelow"Guru99"codeexampleshowshowtousetherequirefunction
varexpress=require('express');
varapp=express();
app.set('viewemngine','jade');
app.get('/',function(req,res)
{
});
varserver=app.listen(3000,function()
{
});
1. Inthefirststatementitself,weareusingthe"require"keywordtoincludetheexpressmodule.The"express"moduleisanoptimizedJavaScriptlibraryforNode.js
development.ThisisoneofthemostcommonlyusedNode.jsmodules.2. Afterthemoduleisincluded,inordertousethefunctionalitywithinthemodule,anobject
needstobecreated.Hereanobjectoftheexpressmoduleiscreated.3. Oncethemoduleisincludedusingthe"require"commandandan"object"iscreated,the
requiredmethodsoftheexpressmodulecanbeinvoked.Hereweareusingthesetcommandtosettheviewengine,whichisusedtosetthetemplatingengineusedinNode.js.Note:-(Justforthereader'sunderstanding,atemplatingengineisanapproachforinjectingvaluesinanapplicationbypickingupdatafromdatafiles.ThisconceptisprettyfamousinAngularJSwhereinthecurlybraces{{key}}isusedtosubstitutesvaluesinthewebpage.Theword'key'inthecurlybracesbasicallydenotesthevariablewhichwillbesubstitutedbyavaluewhenthepageisdisplayed.)
4. Hereweareusingthelistenmethodtomaketheapplicationlistenonaparticularportnumber.
CreatingNPMmodulesNode.jshastheabilitytocreatecustommodulesandallowsyoutoincludethosecustommodulesinyourNode.jsapplication.
Let'slookatasimpleexampleofhowwecancreateourownmoduleandincludethatmoduleinourmainapplicationfile.Ourmodulewilljustdoasimpletaskofadding2numbers.
Let'sfollowthebelowstepstoseehowwecancreatemodulesandincludetheminourapplication.
Step1)Createafilecalled"Addition.js"andincludethebelowcode.Thisfilewillcontainthelogicforyourmodule.
Belowisthecodewhichwouldgointothisfile;
varexports=module.exports={};
exports.AddNumber=function(a,b)
{
returna+b;
};
1. The"exports"keywordisusedtoensurethatthefunctionalitydefinedinthisfilecanactuallybeaccessedbyotherfiles.
2. Wearethendefiningafunctioncalled'AddNumber'.Thisfunctionisdefinedtotake2parameters,aandb.Thefunctionisaddedtothemodule"exports"tomakethefunctionasapublicfunctionthatcanbeaccessedbyotherapplicationmodules.
3. Wearefinallymakingourfunctionreturntheaddedvalueoftheparameters.
Nowthatwehavecreatedourcustommodulewhichhasthefunctionalityofadding2numbers.It'snowtimetocreateanapplication,whichwillcallthismodule.
Inthenextstep,wewillactuallyseehowtocreatetheapplicationwhichwillcallourcustommodule.
Step2)Createafilecalled"app.js,"whichisyourmainapplicationfileandaddthebelowcode
varAddition=require('./Addition.js');
console.log(Addition.AddNumber(1,2));
1. Weareusingthe"require"keywordtoincludethefunctionalityintheAddition.jsfile.2. SincethefunctionsintheAddition.jsfilearenowaccessible,wecannowmakeacallto
theAddNumberfunction.Inthefunction,wearepassing2numbersasparameters.Wearethendisplayingthevalueintheconsole.
Output:
Whenyouruntheapp.jsfile,youwillgetanoutputofvalue3intheconsolelog.TheresultisbecausetheAddNumberfunctionintheAddition.jsfilewascalledsuccessfullyandthereturnedvalueof3wasdisplayedintheconsole.
Note:-Wearenotusingthe"Nodepackagemanager"asofyettoinstallourAddition.jsmodule.Thisisbecausethemoduleisalreadypartofourprojectonthelocalmachine.TheNodepackagemanagercomesinthepicturewhenyoupublishamoduleontheinternetwhichweseeinthesubsequenttopic.
ExtendingmodulesWhencreatingmodules,itisalsopossibletoextendorinheritonemodulefromanother.
Inmoderndayprogramming,it'squitecommontobuildalibraryofcommonmodulesandthenextendthefunctionalityofthesecommonmodulesifrequired.
Let'slookatanexampleofhowwecanextendmodulesinNode.js.
Step1)Createthebasemodule.
Inourexample,createafilecalled"Tutorial.js"andplacethebelowcode.
Inthiscode,wearejustcreatingafunctionwhichreturnsastringtotheconsole.Thestringreturnedis"Guru99Tutorial".
varexports=module.exports={};
exports.tutorial=function()
{
console.log("Guru99Tutotial")
}
1. TheexportsmoduleisusedsothatwhateverfunctionisdefinedinthisfilecanbeavailableinothermodulesinNode.js
2. WearecreatingafunctioncalledtutorialwhichcanbeusedinotherNode.jsmodules.3. Wearedisplayingastring"Guru99Tutorial"intheconsolewhenthisfunctioniscalled.
NowthatwehavecreatedourbasemodulecalledTutorial.js.It'snowtimetocreateanothermodulewhichwillextendthisbasemodule.
Wewillexplorehowtodothisinthenextstep.
Step2)Nextwewillcreateourextendedmodule.Createanewfilecalled"NodeTutorial.js"andplacethebelowcodeinthefile.
varTutor=require('./Tutorial.js');
exports.NodeTutorial=function()
{
console.log("NodeTutorial")
functionpTutor()
{
varPTutor=Tutor
PTutor.tutorial;
}
}
Note,thefollowingkeypointsabouttheabovecode
1. Weareusingthe"require"functioninthenewmodulefileitself.Sincewearegoingtoextendtheexistingmodulefile"Tutorial.js",weneedtofirstincludeitbeforeextendingit.
2. Wethencreateafunctioncalled"Nodetutorial."Thisfunctionwilldo2things,
Itwillsendastring"NodeTutorial"totheconsole.Itwillsendthestring"Guru99Tutorial"fromthebasemodule"Tutorial.js"toourextendedmodule"NodeTutorial.js".
1. Herewearecarryingoutthefirststeptosendastringto"NodeTutorial"totheconsole.2. ThenextstepistocallthefunctionfromourTutorialmodule,whichwilloutputthestring
"Guru99Tutorial"totheconsole.log.
Step3)Createyourmainapp.jsfilewhichisyourmainapplicationfileandincludethebelowcode.
varlocalTutor=require('./NodeTutorial.js');
localTutor.NodeTutorial();
localTutor.NodeTutorial.pTutor();
Theabovecodedoesthefollowingthings;
1. Ourmainapplicationfilenowcallsthe"NodeTutorial"module.2. Wearecallingthe"NodeTutorial"function.Bycallingthisfunction,thetext"Node
Tutorial"willbedisplayedintheconsolelog.3. SincewehaveextendedourTutorial.jsmoduleandexposedafunctioncalledpTutor.It
alsocallsthetutorialmoduleintheTutorial.jsmodule,andthetext"Guru99Tutorial"willbedisplayedtotheconsoleaswell.
Output:
Sincewehaveexecutedtheaboveapp.jscodeusingNode,wewillgetthefollowingoutputintheconsole.logfile
NodeTutorialGuru99Tutorial
PublishingNPM(NodePackageManager)ModulesOnecanpublishtheirownmoduletotheirownGithubrepository.
Bypublishingyourmoduletoacentrallocation,youarethennotburdenedwithhavingtoinstallyourselfoneverymachinethatrequiresit.
Instead,youcanusetheinstallcommandofnpmandinstallyourpublishednpmmodule.
Thefollowingstepsneedtobefollowedtopublishyournpmmodule
Step1)CreateyourrepositoryonGitHub(anonlinecoderepositorymanagementtool).Itcanbeusedforhostingyourcoderepositories.
Step2)Youneedtotellyourlocalnpminstallationonwhoyouare.Whichmeansthatweneedtotellnpmwhoistheauthorofthismodule,whatistheemailidandanycompanyURL,whichisavailablewhichneedstobeassociatedwiththisid.Allofthesedetailswillbeaddedtoyournpmmodulewhenitispublished.
Thebelowcommandssetsthename,emailandURLoftheauthorofthenpmmodule.
npmsetinit.author.name"Guru99."
npmsetinit.author.email"guru99@gmail.com"
npmsetinit.author.urlhttp://Guru99.com
Step3)Thenextstepistologinintonpmusingthecredentialsprovidedinthelaststep.Tologin,youneedtousethebelowcommand
npmlogin
Step4)Initializeyourpackage–Thenextstepistoinitializethepackagetocreatethepackage.jsonfile.Thiscanbedonebyissuingthebelowcommand
npminit
Whenyouissuetheabovecommand,youwillbepromptedforsomequestions.Themostimportantoneistheversionnumberforyourmodule.
Step5)PublishtoGitHub–ThenextstepistopublishyoursourcefilestoGitHub.Thiscanbedonebyrunningthebelowcommands.
gitadd.
gitcommit-m"Initialrelease"
gittagv0.0.1
gitpushoriginmaster--tags
Step6)Publishyourmodule–Thefinalbitistopublishyourmoduleintothenpmregistry.Thisisdoneviathebelowcommand.
npmpublish
ManagingthirdpartypackageswithnpmAswehaveseen,the"Nodepackagemanager"hastheabilitytomanagemodules,whicharerequiredbyNode.jsapplications.
Let'slookatsomeofthefunctionsavailableinthenodepackagemanagerformanagingmodules
1. Installingpackagesinglobalmode–Modulescanbeinstalledatthegloballevel,whichjustbasicallymeansthatthesemoduleswouldbeavailableforallNode.jsprojectsonalocalmachine.Theexamplebelowshowshowtoinstallthe"expressmodule"withtheglobaloption.
npminstallexpress–global
Theglobaloptionintheabovestatementiswhatallowsthemodulestobeinstalledatagloballevel.
2. Listingalloftheglobalpackagesinstalledonalocalmachine.Thiscanbedonebyexecutingthebelowcommandinthecommandpromptnpmlist--global
Belowistheoutputwhichwillbeshown,ifyouhavepreviouslyinstalledthe"expressmodule"onyoursystem.
Hereyoucanseethedifferentmodulesinstalledonthelocalmachine.
3. Installingaspecificversionofapackage–Sometimestheremaybearequirementtoinstalljustthespecificversionofapackage.Onceyouknowwhatisthepackageandtherelevantversionthatneedstobeinstalled,youcanusethenpminstallcommandtoinstallthatspecificversion.Theexamplebelowshowshowtoinstallthemodulecalledunderscorewithaspecificversionof1.7.0
npminstallunderscore@1.7.0
4. Updatingapackageversion–Sometimesyoumayhaveanolderversionofapackageinasystem,andyoumaywanttoupdatetothelatestoneavailableinthemarket.Todothisonecanusethenpmupdatecommand.Theexamplebelowshowshowtoupdatetheunderscorepackagetothelatestversion
npmupdateunderscore
5. Searchingforaparticularpackage–Tosearchwhetheraparticularversionisavailableonthelocalsystemornot,youcanusethesearchcommandofnpm.Theexamplebelowwillcheckiftheexpressmoduleisinstalledonthelocalmachineornot.npmsearchexpress
6. Un-installingapackage–Thesameinwhichyoucaninstallapackage,youcanalsoun-installapackage.Theuninstallationofapackageisdonewiththeuninstallationcommandofnpm.Theexamplebelowshowshowtouninstalltheexpressmodule
npmuninstallexpress
Whatisthepackage.jsonfileThe"package.json"fileisusedtoholdthemetadataaboutaparticularproject.ThisinformationprovidestheNodepackagemanagerthenecessaryinformationtounderstandhowtheprojectshouldbehandledalongwithitsdependencies.
Thepackage.jsonfilescontainsinformationsuchastheprojectdescription,theversionoftheprojectinaparticulardistribution,licenseinformation,andconfigurationdata.
Thepackage.jsonfileisnormallylocatedattherootdirectoryofaNode.jsproject.
Let'stakeanexampleofhowthestructureofamodulelookswhenitisinstalledvianpm.
ThebelowsnapshotshowsthefilecontentsoftheexpressmodulewhenitisincludedinyourNode.jsproject.Fromthesnapshot,youcanseethepackage.jsonfileintheexpressfolder.
Ifyouopenthepackage.jsonfileyouwillseealotofinformationinthefile.
Belowisasnapshotofaportionofthefile.Theexpress@~4.13.1mentionstheversionnumberoftheexpressmodulebeingused.
Summary
AmoduleinNode.jsisalogicalencapsulationofcodeinasingleunit.SeparationintomodulesmakescodemoremanageableandmaintainableforfuturepurposesTherearemanymodulesavailableinthemarketwhichcanbeusedwithinNode.jssuchasexpress,underscore,mongoDB,etc.Thenodepackagemanager(npm)isusedtodownloadandinstallmoduleswhichcanthenbeusedinaNode.jsapplication.OnecancreatecustomNPMmodules,extendthesemodulesandalsopublishthesemodules.TheNodepackagemanagerhasacompletesetofcommandstomanagethenpmmodulesonthelocalsystemsuchastheinstallation,un-installation,searching,etc.Thepackage.jsonfileisusedtoholdtheentiremetadatainformationforannpmmodule.
Chapter4:CreateServerandGetData
TheNode.jsframeworkismostlyusedtocreateserverbasedapplications.Theframeworkcaneasilybeusedtocreatewebserverswhichcanservecontenttousers.
Thereareavarietyofmodulessuchasthe"http"and"request"module,whichhelpsinprocessingserverrelatedrequestsinthewebserverspace.WewillhavealookathowwecancreateabasicwebserverapplicationusingNodejs.
NodeaswebserverusingHTTPLet'slookatanexampleofhowtocreateandrunourfirstNodejsapplication.
Ourapplicationisgoingtocreateasimpleservermodulewhichwilllistenonportno7000.Ifarequestismadethroughthebrowseronthisportno,thenserverapplicationwillsenda'Hello'World'responsetotheclient.
varhttp=require('http')
varserver=http.createServer((function(request,response)
{
response.writeHead(200,
{"Content-Type":"text/plain"));
response.end("HelloWorld\n");
}));
server.listen(7000);
CodeExplanation:
1. Thebasicfunctionalityoftherequirefunctionisthatitreadsajavascriptfile,executesthefile,andthenproceedstoreturntheexportsobject.Soinourcase,sincewewanttousethefunctionalityofthehttpmodule,weusetherequirefunctiontogettherequiredfunctionsfromthehttpmodulesothatitcanbeusedinourapplication.
2. Inthislineofcode,wearecreatingaserverapplicationwhichisbasedonasimplefunction.Thisfunctioniscalledwheneverarequestismadetoourserverapplication.
3. Whenarequestisreceived,wearesayingtosendaresponsewithaheadertypeof'200.'Thisnumberisthenormalresponsewhichissentinanhttpheaderwhenasuccessfulresponseissenttotheclient.
4. Intheresponseitself,wearesendingthestring'HelloWorld.'5. Wearethenusingtheserver.listenfunctiontomakeourserverapplicationlistentoclient
requestsonportno7000.Youcanspecifyanyavailableportoverhere.
Ifthecommandisexecutedsuccessfully,thefollowingOutputwillbeshownwhenyourunyourcodeinthebrowser.
Output:
Fromtheoutput,
YoucanclearlyseethatifwebrowsetotheURLoflocalhostonport7000,youwillseethestring'HelloWorld'displayedinthepage.Becauseinourcodewehavementionedspecificallyfortheservertolistenonportno7000,weareabletoviewtheoutputwhenbrowsingtothisurl.
Hereisthecodeforyourreference
varhttp=require('http')
varserver=http.createServer((function(request,response)
{
response.writeHead(200,
{"Content-Type":"text/plain"));
response.end("HelloWorld\n");
}));
server.listen(7000);
HandlingGETRequestsinNode.jsMakingaGETRequesttogetthedatafromanothersiteisrelativelyverysimpleinNode.js.TomakeaGetrequestinthenode,weneedtofirsthavetherequestmoduleinstalled.Thiscanbedonebyexecutingthefollowinglineinthecommandline
npminstallrequest
TheabovecommandrequeststheNodepackagemanagertodownloadtherequiredrequestmodulesandinstallthemaccordingly.
Whenyournpmmodulehasbeeninstalledsuccessfully,thecommandlinewillshowtheinstalledmodulenameandversion:<name>@<version>.
Intheabovesnapshot,youcanseethatthe'request'modulealongwiththeversionnumber2.67.0wasdownloadedandinstalled.
Nowlet'sseethecodewhichcanmakeuseofthis'request'command.
varrequest=require("request");
request("http://www.google.com",function(error,response,body)
{
console.log(body);
});
CodeExplanation:
1. Weareusingthe'require'modulewhichwasinstalledinthelaststep.ThismodulehasthenecessaryfunctionswhichcanbeusedtomakeGETrequeststowebsites.
2. WearemakingaGETRequesttowww.google.comandsubsequentlycallingafunctionwhenaresponseisreceived.Whenaresponseisreceivedtheparameters(error,response,andbody)willhavethefollowingvaluesa. Error–IncasethereisanyerrorreceivedwhenusingtheGETrequest,thiswillbe
recordedhere.b. Response-Theresponsewillhavethehttpheaderswhicharesentbackinthe
response.c. Body-ThebodywillcontaintheentirecontentoftheresponsesentbyGoogle.
3. Inthis,wearejustwritingthecontentreceivedinthebodyparametertotheconsole.logfile.Sobasically,whateverwegetbygoingtowww.google.comwillbewrittentotheconsole.log.
Hereisthecodeforyourreference
varrequest=require("request");
request("http://www.google.com",function(error,response,body)
{
console.log(body);
});
Summary
TheNode.jsframeworkcanbeusedtodevelopwebserversusingthe'http'module.Theapplicationcanbemadetolistenonaparticularportandsendaresponsetotheclientwheneverarequestismadetotheapplication.The'request'modulecanbeusedtogetinformationfromwebsites.Theinformationwouldcontaintheentirecontentofthewebpagerequestedfromtherelevantwebsite.
Chapter5:Node.jswithExpress
Inthistutorial,wewillalsohavealookattheexpressframework.ThisframeworkisbuiltinsuchawaythatitactsasaminimalandflexibleNode.jswebapplicationframework,providingarobustsetoffeaturesforbuildingsingleandmultipage,andhybridwebapplication.
WhatisExpress.jsExpress.jsisaNodejswebapplicationserverframework,whichisspecificallydesignedforbuildingsingle-page,multi-page,andhybridwebapplications.
Ithasbecomethestandardserverframeworkfornode.js.ExpressisthebackendpartofsomethingknownastheMEANstack.
TheMEANisafreeandopen-sourceJavaScriptsoftwarestackforbuildingdynamicwebsitesandwebapplicationswhichhasthefollowingcomponents;
1)MongoDB-ThestandardNoSQLdatabase
2)Express.js-Thedefaultwebapplicationsframework
3)Angular.js-TheJavaScriptMVCframeworkusedforwebapplications
4)Node.js-Frameworkusedforscalableserver-sideandnetworkingapplications.
TheExpress.jsframeworkmakesitveryeasytodevelopanapplicationwhichcanbeusedtohandlemultipletypesofrequestsliketheGET,PUT,andPOSTandDELETErequests.
InstallingandusingExpressExpressgetsinstalledviatheNodePackagemanager.Thiscanbedonebyexecutingthefollowinglineinthecommandline
npminstallexpress
TheabovecommandrequeststheNodepackagemanagertodownloadtherequiredexpressmodulesandinstallthemaccordingly.
Let'suseournewlyinstalledExpressframeworkandcreateasimple"HelloWorld"application.
Ourapplicationisgoingtocreateasimpleservermodulewhichwilllistenonportno3000.Inourexample,ifarequestismadethroughthebrowseronthisportno,thenserverapplicationwillsenda'Hello'World'responsetotheclient.
varexpress=require('express');
varapp=express();
app.get('/',function(req,res)
{
res.send('HelloWorld!');
});
varserver=app.listen(3000,function(){});
CodeExplanation:
1. Inourfirstlineofcode,weareusingtherequirefunctiontoincludethe"expressmodule."2. Beforewecanstartusingtheexpressmodule,weneedtomakeanobjectoftheexpress
module.3. Herewearecreatingacallbackfunction.Thisfunctionwillbecalledwheneveranybody
browsestotherootofourwebapplicationwhichishttp://localhost:3000.Thecallbackfunctionwillbeusedtosendthestring'HelloWorld'tothewebpage.
4. Inthecallbackfunction,wearesendingthestring"HelloWorld"backtotheclient.The'res'parameterisusedtosendcontentbacktothewebpage.This'res'parameterissomethingthatisprovidedbythe'request'moduletoenableonetosendcontentbacktothewebpage.
5. Wearethenusingthelistentofunctiontomakeourserverapplicationlistentoclientrequestsonportno3000.Youcanspecifyanyavailableportoverhere.3
Ifthecommandisexecutedsuccessfully,thefollowingOutputwillbeshownwhenyourunyourcodeinthebrowser.
Output:
Fromtheoutput,
YoucanclearlyseethatweifbrowsetotheURLoflocalhostonport3000,youwillseethestring'HelloWorld'displayedinthepage.Becauseinourcodewehavementionedspecificallyfortheservertolistenonportno3000,weareabletoviewtheoutputwhenbrowsingtothisURL.
WhatareRoutesRoutingrefersfordeterminingthewayinwhichanapplicationrespondstoaclientrequesttoaparticularendpoint.
Forexample,aclientcanmakeaGET,POST,PUTorDELETEhttprequestforvariousURL'ssuchastheone'sshownbelow;
http://localhost:3000/Books
http://localhost:3000/Students
Intheaboveexample,
IfaGETrequestismadeforthefirstURL,thentheresponseshouldideallybealistofbooks.IftheGETrequestismadeforthesecondURL,thentheresponseshouldideallybealistofStudents.SobasedontheURLwhichisaccessed,adifferentfunctionalityonthewebserverwillbeinvokedandaccordinglytheresponsewillbesenttotheclient.Thisistheconceptofrouting.
Eachroutecanhaveoneormorehandlerfunctions,whichareexecutedwhentherouteismatched.
Thegeneralsyntaxforarouteisshownbelow
app.METHOD(PATH,HANDLER)
Wherein,
1)appisaninstanceoftheexpressmodule
2)METHODisanHTTPrequestmethod(GET,POST,PUTorDELETE)
3)PATHisapathontheserver.
4)HANDLERisthefunctionexecutedwhentherouteismatched.
Let'slookatanexampleofhowwecanimplementroutesinexpress.Ourexamplewillcreate3routesas
1. A/Noderoutewhichwilldisplaythestring"TutorialonNode"ifthisrouteisaccessed2. A/Angularroutewhichwilldisplaythestring"TutorialonAngular"ifthisrouteis
accessed3. Adefaultroute/whichwilldisplaythestring"WelcometoGuru99Tutorials."
Ourbasiccodewillremainthesameaspreviousexamples.Thebelowsnippetisanadd-ontoshowcasehowroutingisimplemented.
app.route('/Node).get(function(req.res)
{
res.send("TutorialonNode");
});
app.route('/Angular).get(function(req.res)
{
res.send("TutorialonAngular");
});
app.get('/',function(req,res)
{
res.send('WelcometoGuru99Tutorials');
});
CodeExplanation:
1. HerewearedefiningarouteiftheURLhttp://localhost:3000/Nodeisselectedinthebrowser.Totheroute,weareattachingacallbackfunctionwhichwillbecalledwhenwebrowsetotheNodeURL.
Thefunctionhas2parameters.
Themainparameterwewillbeusingisthe'res'parameterwhichcanbeusedtosendinformationbacktotheclient.The'req'parameterhasinformationabouttherequestbeingmade.Sometimesadditionalparameterscouldbesentaspartoftherequestbeingmade,andhencethe'req'parametercanbeusedtofindtheadditionalparametersbeingsent.
2. Weareusingthesendfunctiontosendthestring"TutorialonNode"backtotheclientiftheNoderouteischosen.
3. HerewearedefiningarouteiftheURLhttp://localhost:3000/Angularisselectedinthebrowser.Totheroute,weareattachingacallbackfunctionwhichwillbecalledwhenwebrowsetotheAngularURL.
4. Weareusingthesendfunctiontosendthestring"TutorialonAngular"backtotheclientiftheAngularrouteischosen.
5. Thisisthedefaultroutewhichischosenwhenonebrowsestotherouteoftheapplication–http://localhost:3000.Whenthedefaultrouteischosen,themessage"WelcometoGuru99Tutorials"willbesenttotheclient.
Ifthecommandisexecutedsuccessfully,thefollowingOutputwillbeshownwhenyourunyourcodeinthebrowser.
Output:
Fromtheoutput,
YoucanclearlyseethatweifbrowsetotheURLoflocalhostonport3000,youwillseethestring'WelcometoGuru99Tutorials'displayedonthepage.Becauseinourcode,wehavementionedthatourdefaultURLwoulddisplaythismessage.
Fromtheoutput,
YoucanseethatiftheURLhasbeenchangedto/Node,therespectiveNoderoutewouldbechosenandthestring"TutorialOnNode'isdisplayed.
Fromtheoutput,
YoucanseethatiftheURLhasbeenchangedto/Angular,therespectiveNoderoutewouldbechosenandthestring"TutorialOnAngular"isdisplayed.
SampleWebserverusingexpress.jsFromouraboveexample,wehaveseenhowwecandecideonwhatoutputtoshowbasedonrouting.Thissortofroutingiswhatisusedinmostmoderndaywebapplications.TheotherpartofawebserverisaboutusingtemplatesinNodejs.
Whencreatingquickon-the-flyNodeapplications,aneasyandfastwayistousetemplatesfortheapplication.Therearemanyframeworksavailableinthemarketformakingtemplates.Inourcase,wewilltaketheexampleofthejadeframeworkfortemplating.
JadegetsinstalledviatheNodePackagemanager.Thiscanbedonebyexecutingthefollowinglineinthecommandline
npminstalljade
TheabovecommandrequeststheNodepackagemanagertodownloadtherequiredjademodulesandinstallthemaccordingly.
Let'suseournewlyinstalledjadeframeworkandcreatesomebasictemplates.
Step1)Thefirststepistocreateajadetemplate.Createafilecalledindex.jadeandinsertthebelowcode
1. Herewearespecifyingthatthetitleofthepagewillbechangedtowhatevervalueispassedwhenthistemplategetsinvoked.
2. Wearealsospecifyingthatthetextintheheadertagwillgetreplacedtowhatevergetspassedinthejadetemplate.
varexpress=require('express');
varapp=express();
app.set('viewengine','jade');
app.get('/',function(req,res)
{
res.render('index',
{title:'Guru99',message:'Welcome'})
});
varserver=app.listen(3000,function(){});
CodeExplanation:
1. Thefirstthingtospecifyintheapplicationis"viewengine"thatwillbeusedtorenderthetemplates.Sincewearegoingtousejadetorenderourtemplates,wespecifythisaccordingly.
2. Therenderfunctionisusedtorenderawebpage.Inourexample,wearerenderingthetemplate(index.jade)whichwascreatedearlier.
3. Wearepassingthevaluesof"Guru99"and"Welcome"totheparameters"title"and"message"respectively.Thesevalueswillbereplacedbythe'title',and'message'parametersdeclaredintheindex.jadetemplate.
Ifthecommandisexecutedsuccessfully,thefollowingOutputwillbeshownwhenyourunyourcodeinthebrowser.
Output:
Fromtheoutput,
Wecanseethatthetitleofthepagegetssetto"Guru99"andtheheaderofthepagegetssetto"Welcome."Thisisbecauseofthejadetemplatewhichgetsinvokedinournodejsapplication.
Summary
TheexpressframeworkisthemostcommonframeworkusedfordevelopingNodejsapplications.Theexpressframeworkisbuiltontopofthenode.jsframeworkandhelpsinfast-trackingdevelopmentofserverbasedapplications.Routesareusedtodivertuserstodifferentpartsofthewebapplicationsbasedontherequestmade.Theresponseforeachroutecanbevarieddependingonwhatneedstobeshowntotheuser.Templatescanbeusedtoinjectcontentinanefficientmanner.JadeisoneofthemostpopulartemplatingenginesusedinNode.jsapplications.
Chapter6:Node.jswithMongoDB
Mostlyallmoderndaywebapplicationshavesomesortofdatastoragesystematthebackendtostoredata.Forexample,ifyoutakethecaseofawebshoppingapplication,datasuchasthepriceofanitemorthenumberofitemsofaparticulartypewouldbestoredinthedatabase.
TheNodejsframeworkhastheabilitytoworkwithdatabaseswhicharecommonlyrequiredbymostmoderndaywebapplications.Nodejscanworkwithbothrelational(suchasOracleandMSSQLServer)andnon-relationaldatabases(suchasMongoDBandMySQL).Duringthistutorial,wewillseehowwecanusedatabasesfromwithinNodejsapplications.
Node.jsandNoSQLDatabasesOvertheyears,NoSQLdatabasesuchasMongoDBandMySQLhavebecomequitepopularasdatabasesforstoringdata.Theabilityofthesedatabasestostoreanysortofcontentandparticularlyinanysortofformatiswhatmakesthesedatabasessofamous.
Node.jshastheabilitytoworkwithbothMySQLandMongoDBasdatabases.Inordertouseeitherofthesedatabases,youneedtodownloadandusetherequiredmodulesusingtheNodepackagemanager.
ForMySQL,therequiredmoduleiscalled"mysql"andforusingMongoDBtherequiredmoduletobeinstalledis"Mongoose."
Withthesemodules,youcanperformthefollowingoperationsinNode.js
1. Managetheconnectionpooling–HereiswhereyoucanspecifythenumberofMySQLdatabaseconnectionsthatshouldbemaintainedandsavedbyNode.js.
2. Createandcloseaconnectiontoadatabase.Ineithercase,youcanprovideacallbackfunctionwhichcanbecalledwheneverthe"create"and"close"connectionmethodsareexecuted.
3. Queriescanbeexecutedtogetdatafromrespectivedatabasestoretrievedata.4. Datamanipulationsuchasinsertingdata,deletingandupdatingdatacanalsobeachieved
withthesemodules.
Fortheremainingtopics,wewilllookathowwecanworkwithMongoDBdatabaseswithinNode.js.
UsingMongoDBandNode.jsAsdiscussedintheearliertopic,MongoDBisoneofthemostpopulardatabasesusedalongwithNode.js.
Duringthischapter,wewillsee
HowwecanestablishconnectionswithaMongoDBdatabase
Howwecanperformthenormaloperationsofreadingdatafromadatabaseaswellasinserting,deletingandupdatingrecordsinamongoDBdatabase.
Forthepurposeofthischapter,let'sassumethatwehavethebelowmongoDBdatainplace.
Databasename:EmployeeDB
Collectionname:Employee
Documents
{
{Employeeid:1,EmployeeName:Guru99},
{Employeeid:2,EmployeeName:Joe},
{Employeeid:3,EmployeeName:Martin},
}
1. InstallingtheNPMModulesToaccessMongofromwithinaNodeapplication,adriverisrequired.TherearenumberofMongodriversavailable,butMongoDBisamongthemostpopular.ToinstalltheMongoDBmodule,runthebelowcommandnpminstallmongodb
2. CreatingandclosingaconnectiontoaMongoDBdatabase.ThebelowcodesnippetshowshowtocreateandcloseaconnectiontoaMongoDBdatabase.
varMongoClient=require('mongodb').MongoClient;
varurl='mongodb://localhost/EmployeeDB';
MongoClient.connect(url,function(err,db){
cursor.log("connected");
db.close();
});
CodeExplanation:
1. Thefirststepistoincludethemongoosemodulewhichisdonethroughtherequirefunction.Oncethismoduleisinplace,wecanusethenecessaryfunctionsavailableinthismoduletocreateconnectionstothedatabase.
2. Nextwespecifyourconnectstringtothedatabase.Intheconnectstringthereare3keyvalueswhicharepassed.
Thefirstis'mongodb'whichspecifiesthatweareconnectingtoamongoDBdatabase.Thenextis'localhost'whichmeansweareconnectingtoadatabaseonthelocalmachine.Thenextis'EmployeeDB'whichisthenameofthedatabasedefinedinourMongoDBdatabase.
3. Thenextstepistoactuallyconnecttoourdatabase.TheconnectfunctiontakesinourURLandhasthefacilitytospecifyacallbackfunction.Itwillbecalledwhentheconnectionisopenedtothedatabase.Thisgivesustheopportunitytoknowifthedatabaseconnectionwassuccessfulornot.
4. Inthefunction,wearewritingthestring"Connectionestablished"totheconsoletoindicatethatasuccessfulconnectionwascreated.
5. Finally,weareclosingtheconnectionusingthedb.closestatement.
Iftheabovecodeisexecutedproperly,thestring"Connected"willbewrittentotheconsoleasshownbelow.
3. QueryingfordatainaMongoDBdatabase–UsingtheMongoDBdriverwecanalsofetchdatafromtheMongoDBdatabase.
ThebelowsectionwillshowhowwecanusethedrivertofetchallofthedocumentsfromourEmployeecollection(ThisisthecollectioninourMongoDBdatabasewhichcontainsalltheemployeerelateddocuments.Eachdocumenthasanobjectid,Employeenameandemployeeidtodefinethevaluesofthedocument)inourEmployeeDBdatabase.
varMongoClient=require('mongodb').MongoClient;
varurl='mongodb://localhost/EmployeeDB';
MongoClient.connect(url,function(err,db){
varcursor=db.collection('Employee').find();
cursor.each(function(err,doc){
console.log(doc);
});
});
CodeExplanation:
1. Inthefirststep,wearecreatingacursor(Acursorisapointerwhichisusedtopointtothevariousrecordsfetchedfromadatabase.Thecursoristhenusedtoiteratethroughthedifferentrecordsinthedatabase.Herewearedefiningavariablenamecalledcursorwhichwillbeusedtostorethepointertotherecordsfetchedfromthedatabase.)whichpointstotherecordswhicharefetchedfromtheMongoDbcollection.Wealsohavethefacilityofspecifyingthecollection'Employee'fromwhichtofetchtherecords.Thefind()functionisusedtospecifythatwewanttoretrieveallofthedocumentsfromtheMongoDBcollection.
2. Wearenowiteratingthroughourcursorandforeachdocumentinthecursorwearegoingtoexecuteafunction.
3. Ourfunctionissimplygoingtoprintthecontentsofeachdocumenttotheconsole.
Note:-Itisalsopossibletofetchaparticularrecordfromadatabase.Thiscanbedonebyspecifyingthesearchconditioninthefind()function.Forexample,supposeifyoujustwantedtofetchtherecordwhichhastheemployeenameasGuru99thenthisstatementcanbewrittenasfollows"varcursor=db.collection('Employee').find()."
Iftheabovecodeisexecutedsuccessfully,thefollowingoutputwillbedisplayedinyourconsole.
Output:
Fromtheoutput,
Youwillbeabletoclearlyseethatallthedocumentsfromthecollectionareretrieved.Thisispossiblebyusingthefind()methodofthemongoDBconnection(db)anditeratingthroughallofthedocumentsusingthecursor.
4. Insertingdocumentsinacollection–DocumentscanbeinsertedintoacollectionusingtheinsertOnemethodprovidedbytheMongoDBlibrary.ThebelowcodesnippetshowshowwecaninsertadocumentintoamongoDBcollection.
varMongoClient=require('mongodb').MongoClient;
varurl='mongodb://localhost/EmployeeDB';
MongoClient.connect(url,function(err,db){
db.collection('Employee').insertOne({
Employeeid:4,
EmployeeName:"NewEmployee"
});
});
CodeExplanation:
1. HereweareusingtheinsertOnemethodfromtheMongoDBlibrarytoinsertadocumentintotheEmployeecollection.
2. WearespecifyingthedocumentdetailsofwhatneedstobeinsertedintotheEmployeecollection.
IfyounowcheckthecontentsofyourMongoDBdatabase,youwillfindtherecordwithEmployeeidof4andEmployeeNameof"NewEmployee"insertedintotheEmployeecollection.
Note:Theconsolewillnotshowanyoutputbecausetherecordisbeinginsertedinthedatabaseandnooutputcanbeshownhere.
Tocheckthatthedatahasbeenproperlyinsertedinthedatabase,youneedtoexecutethefollowingcommandsinMongoDB
1. UseEmployeeDB2. db.Employee.find({Employeeid:4})
ThefirststatementensuresthatyouareconnectedtotheEmployeeDbdatabase.Thesecondstatementsearchesfortherecordwhichhastheemployeeidof4.
5. Updatingdocumentsinacollection-DocumentscanbeupdatedinacollectionusingtheupdateOnemethodprovidedbytheMongoDBlibrary.ThebelowcodesnippetshowshowtoupdateadocumentinamongoDBcollection.
varMongoClient=require('mongodb').MongoClient;
varurl='mongodb://localhost/EmployeeDB';
MongoClient.connect(url,function(err,db){
db.collection('Employee').updateOne({
"EmployeeName":"NewEmployee"
},{
$set:{
"EmployeeName":"Mohan"
}
});
});
CodeExplanation:
1. Hereweareusingthe"updateOne"methodfromtheMongoDBlibrary,whichisusedtoupdateadocumentinamongoDBcollection.
2. Wearespecifyingthesearchcriteriaofwhichdocumentneedstobeupdated.Inourcase,wewanttofindthedocumentwhichhastheEmployeeNameof"NewEmployee."
3. WethenwanttosetthevalueoftheEmployeeNameofthedocumentfrom"NewEmployee"to"Mohan".
IfyounowcheckthecontentsofyourMongoDBdatabase,youwillfindtherecordwithEmployeeidof4andEmployeeNameof"Mohan"updatedintheEmployeecollection.
Tocheckthatthedatahasbeenproperlyupdatedinthedatabase,youneedtoexecutethefollowingcommandsinMongoDB
1. UseEmployeeDB2. db.Employee.find({Employeeid:4})
ThefirststatementensuresthatyouareconnectedtotheEmployeeDbdatabase.Thesecondstatementsearchesfortherecordwhichhastheemployeeidof4.
6. Deletingdocumentsinacollection-Documentscanbedeletedinacollectionusingthe"deleteOne"methodprovidedbytheMongoDBlibrary.ThebelowcodesnippetshowshowtodeleteadocumentinamongoDBcollection.
varMongoClient=require('mongodb').MongoClient;
varurl='mongodb://localhost/EmployeeDB';
MongoClient.connect(url,function(err,db){
db.collection('Employee').deleteOne(
{
"EmployeeName":"Mohan"
}
);
});
CodeExplanation:
1. Hereweareusingthe"deleteOne"methodfromtheMongoDBlibrary,whichisusedtodeleteadocumentinamongoDBcollection.
2. Wearespecifyingthesearchcriteriaofwhichdocumentneedstobedeleted.Inourcase,wewanttofindthedocumentwhichhastheEmployeeNameof"Mohan"anddeletethisdocument.
IfyounowcheckthecontentsofyourMongoDBdatabase,youwillfindtherecordwithEmployeeidof4andEmployeeNameof"Mohan"deletedfromtheEmployeecollection.
Tocheckthatthedatahasbeenproperlyupdatedinthedatabase,youneedtoexecutethefollowingcommandsinMongoDB
1. UseEmployeeDB2. db.Employee.find()
ThefirststatementensuresthatyouareconnectedtotheEmployeeDbdatabase.Thesecondstatementsearchesanddisplayalloftherecordsintheemployeecollection.Hereyoucanseeiftherecordhasbeendeletedornot.
HowtobuildanodeexpressappwithMongoDBtostoreandservecontentBuildinganapplicationwithacombinationofbothusingexpressandMongoDBisquitecommonnowadays.
WhenworkingwithJavaScriptwebbasedapplications,onewillnormallyhereofthetermMEANstack.
ThetermMEANstackreferstoacollectionofJavaScriptbasedtechnologiesusedtodevelopwebapplications.MEANisanacronymforMongoDB,ExpressJS,AngularJSandNode.js.
Hence,it'salwaysgoodtounderstandhowNode.jsandMongoDBworktogethertodeliverapplicationswhichinteractwithbackenddatabases.
Let'slookatasimpleexampleofhowwecanuse"express"and"MongoDB"together.OurexamplewillmakeuseofthesameEmployeecollectionintheMongoDBEmployeeDBdatabase.
WewillnowincorporateExpresstodisplaythedataonourwebpagewhenitisrequestedbytheuser.WhenourapplicationrunsonNode.js,onemightneedtobrowsetotheURLhttp://localhost:3000/Employeeid.
Whenthepageislaunched,alltheemployeeidintheEmployeecollectionwillbedisplayed.Solet'sseethecodesnippetinsectionswhichwillallowustoachievethis.
Step1)Defineallthelibrarieswhichneedtobeusedinourapplication,whichinourcaseisboththeMongoDBandexpresslibrary.
CodeExplanation:
1. Wearedefiningour'express'library,whichwillbeusedinourapplication.2. Wearedefiningour'express'library,whichwillbeusedinourapplicationforconnecting
toourMongoDBdatabase.3. HerewearedefiningtheURLofourdatabasetoconnectto.4. Finally,wearedefiningastringwhichwillbeusedtostoreourcollectionofemployeeid
whichneedtobedisplayedinthebrowserlateron.
Step2)Inthisstep,wearenowgoingtogetalloftherecordsinour'Employee'collectionandworkwiththemaccordingly.
CodeExplanation:
1. Wearecreatingaroutetoourapplicationcalled'Employeeid.'Sowheneveranybodybrowsestohttp://localhost:3000/Employeeidofourapplication,thecodesnippetdefinedforthisroutewillbeexecuted.
2. Herewearegettingalloftherecordsinour'Employee'collectionthroughthedb.collection('Employee').find()command.Wearethenassigningthiscollectiontoavariablecalledcursor.Usingthiscursorvariable,wewillbeabletobrowsethroughalloftherecordsofthecollection.
3. Wearenowusingthecursor.each()functiontonavigatethroughalloftherecordsofourcollection.Foreachrecord,wearegoingtodefineacodesnippetonwhattodowheneachrecordisaccessed.
4. Finally,weseethatiftherecordreturnedisnotnull,thenwearetakingtheemployeeviathecommand"item.Employeeid".TherestofthecodeisjusttoconstructaproperHTMLcodewhichwillallowourresultstobedisplayedproperlyinthebrowser.
Step3)Inthisstep,wearegoingtosendouroutputtothewebpageandmakeourapplicationlistenonaparticularport.
CodeExplanation:
1. Herewearesendingtheentirecontentwhichwasconstructedintheearliersteptoourwebpage.The'res'parameterallowsustosendcontenttoourwebpageasaresponse.
2. WearemakingourentireNode.jsapplicationlistenonport3000.
Output:
Fromtheoutput,
Itclearlyshowsthatalloftheemployeeid'sintheEmployeecollectionwereretrieved.ThisisbecauseweusetheMongoDBdrivertoconnecttothedatabaseandretrievealltheEmployeerecordsandsubsequentlyused"express"todisplaytherecords.
Hereisthecodeforyourreference
varexpress=require('express');
varapp=express();
varMongoClient=require('mongodb').MongoClient;
varurl='mongodb://localhost/EmployeeDB';
varstr="";
app.route('/Employeeid').get(function(req,res)
{
MongoClient.connect(url,function(err,db){
varcursor=db.collection('Employee').find();
//noinspectionJSDeprecatedSymbols
cursor.each(function(err,item){
if(item!=null){
str=str+"Employeeid"+item.Employeeid+"";
}
});
res.send(str);
db.close();
});
});
varserver=app.listen(3000,function(){});
Note:cursor.eachmaybedeprecatedbasedonversionofyourMongoDBdriver.Youcanappend//noinspectionJSDeprecatedSymbolsbeforecursor.eachtocircumventtheissue.Alternatively,youcanuseforEach.BelowisthesamplecodeusingforEach
varexpress=require('express');
varapp=express();
varMongoClient=require('mongodb').MongoClient;
varurl='mongodb://localhost/EmployeeDB';
varstr="";
app.route('/Employeeid').get(function(req,res){
MongoClient.connect(url,function(err,db){
varcollection=db.collection('Employee');
varcursor=collection.find({});
str="";
cursor.forEach(function(item){
if(item!=null){
str=str+"Employeeid"+item.Employeeid+"";
}
},function(err){
res.send(str);
db.close();
}
);
});
});
varserver=app.listen(8080,function(){});
Summary
Node.jsisusedinconjunctionwithNoSQLdatabasestobuildalotofmoderndayswebapplications.SomeofthecommondatabasesusedareMySQLandMongoDB.OneofthecommonmodulesusedforworkingwithMongoDBdatabasesisamodulecalled'MongoDB.'ThismoduleisinstalledviatheNodepackagemanager.WiththeMongoDBmodule,it'spossibletoqueryforrecordsinacollectionandperformthenormalupdate,deleteandinsertoperations.Finally,oneofthemodernpracticesistousetheexpressframeworkalongwithMongoDBtodelivermoderndayapplications.TheExpressframeworkcanmakeuseofthedatareturnedbytheMongoDBdriveranddisplaythedatatotheuserinthewebpageaccordingly.
Chapter7:Promise,Generator,EventandFilestream
Inprevioustutorials,youwouldhaveseencallbackfunctionswhichareusedforAsynchronousevents.Butsometimescallbackfunctionscanbecomeanightmarewhentheystartbecomingnested,andtheprogramstartstobecomelongandcomplex.
Insuchcases,Node.jsprovidesadditionalfeaturestorectifyproblemswhichareencounteredwhenusingcallbacks.TheseareclassifiedintoPromises,generatesandevents.Duringthecourseofthistutorial,wewilllearnandseetheseconceptsinfurtherdetail.
WhatarepromisesBeforewestartwithpromises,let'sfirstrevisitwhatare"callback"functionsinNode.js.Wehaveseenthesecallbackfunctionsalotinthepreviouschapters,solet'squicklygothroughoneofthem.
Theexamplebelowshowsacodesnippet,whichisusedtoconnecttoaMongoDBdatabaseandperformanupdateoperationononeoftherecordsinthedatabase.
1. Intheabovecode,thepartofthefunction(err,db)isknownasthedeclarationofananonymousorcallbackfunction.WhentheMongoClientcreatesaconnectiontotheMongoDBdatabase,itwillreturntothecallbackfunctiononcetheconnectionoperationiscompleted.Soinasense,theconnectionoperationshappensinthebackground,andwhenitisdone,itcallsourcallbackfunction.RememberthatthisisoneofthekeypointsofNode.jstoallowmanyoperationstohappenconcurrentlyandthusnotblockanyuserfromperforminganoperation.
2. Thesecondcodeblockiswhatgetsexecutedwhenthecallbackfunctionisactuallycalled.ThecallbackfunctionjustupdatesonerecordinourMongoDBdatabase.
Sowhatisapromisethen?Well,apromiseisjustanenhancementtocallbackfunctionsinNode.js.Duringthedevelopmentlifecycle,theremaybeaninstancewhereyouwouldneedto
nestmultiplecallbackfunctionstogether.Thiscangetkindofmessyanddifficulttomaintainatacertainpointintime.Inshort,apromiseisanenhancementtocallbacksthatlookstowardsalleviatingtheseproblems.
Thebasicsyntaxofapromiseisshownbelow;
varpromise=doSomethingAync()
promise.then(onFulfilled,onRejected)
"doSomethingAync"isanycallbackorasynchronousfunctionwhichdoessomesortofprocessing.Thistime,whendefiningthecallback,thereisavaluewhichisreturnedcalleda"promise."Whenapromiseisreturned,itcanhave2outputs.Thisisdefinedbythe'thenclause'.Eithertheoperationcanbeasuccesswhichisdenotedbythe'onFulfilled'parameter.Oritcanhaveanerrorwhichisdenotedbythe'onRejected'parameter.
Note:Sothekeyaspectofapromiseisthereturnvalue.ThereisnoconceptofareturnvaluewhenworkingwithnormalcallbacksinNode.js.Becauseofthereturnvalue,wehavemorecontrolofhowthecallbackfunctioncanbedefined.
Inthenexttopic,wewillseeanexampleofpromisesandhowtheybenefitfromcallbacks.
CallbackstopromisesNowlet'slookatanexampleofhowwecanuse"promises"fromwithinaNode.jsapplication.InordertousepromisesinaNode.jsapplication,the'promise'modulemustfirstbedownloadedandinstalled.
Wewillthenmodifyourcodeasshownbelow,whichupdatesanEmployeenameinthe'Employee'collectionbyusingpromises.
Step1)InstallingtheNPMModules
TousePromisesfromwithinaNodeJSapplication,thepromisemoduleisrequired.Toinstallthepromisemodule,runthebelowcommand
npminstallpromise
Step2)Modifythecodetoincludepromises
varPromise=require('promise');
varMongoClient=require('mongodb').MongoClient;
varurl='mongodb://localhost/EmployeeDB';
MongoClient.connect(url)
.then(function(err,db){
db.collection('Employee').updateOne({
"EmployeeName":"Martin"
},{
$set:{
"EmployeeName":"Mohan"
}
});
});
CodeExplanation:-
1. Thefirstpartistoincludethe'promise'modulewhichwillallowustousethepromisefunctionalityinourcode.
2. Wecannowappendthe'then'functiontoourMongoClient.connectfunction.Sowhatthisdoesisthatwhentheconnectionisestablishedtothedatabase,weneedtoexecutethecodesnippetdefinedthereafter.
3. Finally,wedefineourcodesnippetwhichdoestheworkofupdatingEmployeeNameoftheemployeewiththenameof"Martin"to"Mohan".
Note:-
IfyounowcheckthecontentsofyourMongoDBdatabase,youwillfindthatifarecordwithEmployeeNameof"Martin"exists,itwillbeupdatedto"Mohan."
Tocheckthatthedatahasbeenproperlyinsertedinthedatabase,youneedtoexecutethefollowingcommandsinMongoDB
1. UseEmployeeDB2. db.Employee.find({EmployeeName:Mohan})
ThefirststatementensuresthatyouareconnectedtotheEmployeeDbdatabase.Thesecondstatementsearchesfortherecordwhichhastheemployeenameof"Mohan".
DealingwithnestedpromisesWhendefiningpromises,itneedstobenotedthatthe"then"methoditselfreturnsapromise.Soinasense,promisescanbenestedorchainedtoeachother.
Intheexamplebelow,weusechainingtodefine2callbackfunctions,bothofwhichinsertarecordintotheMongoDBdatabase.
(Note:Chainingisaconceptusedtolinkexecutionofmethodstooneanother.Supposeifyourapplicationhad2methodscalled'methodA'and'methodB.'Andthelogicwassuchthat'methodB'shouldbecalledafter'methodA,'thenyouwouldchaintheexecutioninsuchawaythat'methodB'getscalleddirectlyafter'methodA.')
Thekeythingtonoteinthisexampleisthatthecodebecomescleaner,readableandmaintainablebyusingnestedpromises.
varPromise=require('promise');
varMongoClient=require('mongodb').MongoClient;
varurl='mongodb://localhost/EmployeeDB';
MongoClient.connect(url)
.then(function(db){
db.collection('Employee').insertOne({
Employeeid:4,
EmployeeName:"NewEmployee"
})
.then(function(db1){
db1.collection('Employee').insertOne({
Employeeid:5,
EmployeeName:"NewEmployee1"
})
})
});
CodeExplanation:-
1. Wearenowdefining2"then"clauseswhichgetexecutedoneaftertheother.Inthefirstthenclause,wearepassingthe'db'parameterwhichcontainsourdatabaseconnection.Wearethenusingthecollectionpropertyofthe'db'connectiontoinsertrecordsintothe'Employee'collection.The'insertOne'methodisusedtoinserttheactualdocumentintotheEmployeecollection.
2. Wearethenusingthe2ndthenclausealsotoinsertanotherrecordintothedatabase.
IfyounowcheckthecontentsofyourMongoDBdatabase,youwillfindthe2record'sinsertedintotheMongoDBdatabase.
GeneratingpromiseswiththeBlueBirdlibraryBluebirdisafully-featuredPromiselibraryforJavaScript.ThestrongestfeatureofBluebirdisthatitallowsyouto"promisify"otherNodemodulesinordertousethemasynchronously.Promisifyisaconceptappliedtocallbackfunctions.Thisconceptisusedtoensurethateverycallbackfunctionwhichiscalledreturnssomesortofvalue.
SoifaNodeJSmodulecontainsacallbackfunctionwhichdoesnotreturnavalue,ifwePromisifythenodemodule,allthefunction'sinthatspecificnodemodulewouldautomaticallybemodifiedtoensurethatitreturnsavalue.
SoyoucanuseBlueBirdtomaketheMongoDBmodulerunasynchronously.ThisjustaddsanotherlevelofeasewhenwritingNode.jsapplications.
Wewilllookatanexampleofhowtousethebluebirdmodule.
Ourexamplewillfirstestablishaconnectiontothe"Employeecollection"inthe"EmployeeDB"database.If"then"connectionisestablished,thenitwillgetalloftherecordsinthecollectionanddisplaythemintheconsoleaccordingly.
Step1)InstallingtheNPMModules
TouseBluebirdfromwithinaNodeapplication,theBluebirdmoduleisrequired.ToinstalltheBluebirdmodule,runthebelowcommand
npminstallbluebird
Step2)ThenextstepistoincludethebluebirdmoduleinyourcodeandpromisifytheentireMongoDBmodule.Bypromisify,wemeanthatbluebirdwillensurethateachandeverymethoddefinedintheMongoDBlibraryreturnsapromise.
CodeExplanation:-
1. TherequirecommandisusedtoincludetheBluebirdlibrary.2. UseBluebird's.promisifyAll()methodtocreateanasyncversionofeverymethodthe
MongoDBmoduleprovides.ThisensuresthateachmethodoftheMongoDBmodulewillruninthebackgroundandensurethatapromiseisreturnedforeachmethodcallintheMongoDBlibrary.
Step3)Thefinalstepistoconnecttoourdatabase,retrievealltherecordsinourcollectionanddisplaytheminourconsolelog.
CodeExplanation:-
1. Youwillnoticethatweareusingthe"connectAsync"methodinsteadofthenormalconnectionmethodforconnectingtothedatabase.BluebirdactuallyaddstheAsynckeywordtoeachmethodintheMongoDBlibrarytodistinguishthosecallswhichreturnpromisesandthosewhichdon't.SothereisnoguaranteethatmethodswithouttheAsyncwordwillreturnavalue.
2. SimilartotheconnectAsyncmethod,wearenowusingthefindAsyncmethodtoreturnalloftherecordsinthemongoDB'Employee'collection.
3. Finally,ifthefindAsyncreturnsasuccessfulpromisewethendefineablockofcodetoiteratethrougheachrecordinthecollectionanddisplaythemintheconsolelog.
Iftheabovestepsarecarriedoutproperly,allofthedocumentsintheEmployeecollectionwillbedisplayedintheconsoleasshownintheoutputbelow.
Hereisthecodeforyourreference
varPromise=require('bluebird');
varmongoClient=Promise.promisifyAll(require('mongodb')).MongoClient;
varurl='mongodb://localhost/EmployeeDB';
mongoClient.connectAsync('mongodb://localhost/EmployeeDB')
.then(function(db){
returndb.collection('Employee').findAsync({})
})
.then(function(cursor){
cursor.each(function(err,doc){
console.log(doc);
})
});
CreatingacustompromiseAcustompromisecanbecreatedbyusinganodemodulecalled'q.'The'q'libraryneedstobedownloadedandinstalledusingthenodepackagemanager.Afterusingthe'q'library,themethod"denodeify"canbecalledwhichwillcauseanyfunctiontobecomeafunctionwhichreturnsapromise.
Intheexamplebelow,wewillcreateasimplefunctioncalled"Add"whichwilladd2numbers.Wewillconvertthisfunctionintoafunctiontoreturnapromise.
Oncethatisdone,wewillusethepromisereturnedbytheAddfunctiontodisplayamessageintheconsole.log.
Let'sfollowthebelowstepstocreatingourcustomfunctiontoreturnapromise.
Step1)InstallingtheNPMModules
Touse'q'fromwithinaNodeJSapplication,the'q'moduleisrequired.Toinstallthe'q'module,runthebelowcommand
npminstallq
Step2)Definethefollowingcodewhichwillbeusedtocreatethecustompromise.
varQ=require('q');
functionAdd(){
vara,b,c;
a=5;b=6;
c=a+b;
}
varDisplay_promise=Q.denodeify(Add);
varpromise=Add;
promise.then
{console.log("Additionfunctioncomplete");}
CodeExplanation:-
1. Thefirstbitistoincludethe'q'librarybyusingtherequirekeyword.Byusingthislibrary,wewillbeabletodefineanyfunctiontoreturnacallback.
2. WearecreatingafunctioncalledAddwhichwilladd2numbersdefinedinvariablesaandb.Thesumofthesevalueswillbestoredinvariablec.
3. Wearethenusingtheqlibrarytodenodeify(themethodusedtoconvertanyfunctionintoafunctionthatwouldreturnapromise)ourAddfunctionorinotherwiseconvertourAddfunctiontoafunctionwhichreturnsapromise.
4. Wenowcallour"Add"functionandareabletogetareturnpromisevaluebecauseofthepriorstepweperformedofdenodeifytheAddfunction.
5. The'then'keywordisusedspecifythatifthefunctionisexecutedsuccessfullythendisplaythestring"Additionfunctioncompleted"intheconsole.log.
Whentheabovecodeisrun,theoutput"Additionfunctioncompleted"willbedisplayedintheconsole.logasshownbelow.
WhataregeneratorsGeneratorshavebecomequitefamousinNode.jsinrecenttimesandthatprobablybecauseofwhattheyarecapableofdoing.
Generatorsarefunctionexecutionsthatcanbesuspendedandresumedatalaterpoint.Generatorsareusefulwhencarryingoutconceptssuchas'lazyexecution'.Thisbasicallymeansthatbysuspendingexecutionandresumingatwill,weareabletopullvaluesonlywhenweneedto.
Generatorshavethebelow2keymethods
1. Yieldmethod–Theyieldmethodiscalledinafunctiontohalttheexecutionofthefunctionatthespecificlinewheretheyieldmethodiscalled.
2. Nextmethod–Thismethodiscalledfromthemainapplicationtoresumetheexecutionofafunctionwhichhasayieldmethod.Theexecutionofthefunctionwillcontinuetillthenextyieldmethodortilltheendofthemethod.
Let'slookatanexampleofhowgeneratorscanbeused.
Inourexample,wearegoingtohaveasimpleAddfunctionwhichwilladd2numbers,butwewillkeeponhaltingthemethodexecutionatdifferentpointstoshowcasehowgeneratorscanbeused.
function*Add(x){
yieldx+1;
vary=yield(null);
y=6
returnx+y;
}
vargen=Add(5);
gen.next();
gen.next();
CodeExplanation:-
1. Thefirststepistodefineourgenerator"function".Notethatthisisdonebyaddinga"*"tothefunctionkeyword.WearethendefiningafunctioncalledAddwhichtakesa
parameterofx.2. Theyieldkeywordisaspecifictogenerators.Thismakesitapowerfulconstructfor
pausingafunctioninthemiddleofanything.Sohere,thefunctionexecutionwillbehaltedtillweinvokethenext()function,whichwillbedoneinStep4.Atthispoint,thevalueofxwillbecome6andtheexecutionofthefunctionwillbestopped.
3. Thisiswherewefirstcallthegeneratorfunctionandsendthevalueof5toourAddfunction.ThisvaluewillbesubstitutedinthexparameterofourAddfunction.
4. Oncewecallthenext()function,theAdd()functionwillresumetheexecution.Whenthenextstatementvary=yield(null)willbeexecuted,theAdd()functionwillagainstopexecuting.
5. Nowaftercallingthenext()functionagain,thenextstatementswillrun,andthecombinedvalueofx=6andy=6willbeaddedandreturned.
Callbacksvs.generatorsGeneratorsareusedtosolvetheproblemofwhatisknownascallbackhell.SometimescallbackfunctionsbecomesonestedduringthedevelopmentofaNode.jsapplicationthatitjustbecomestoocomplicatedtousecallbackfunctions.
Thisiswheregeneratorsareuseful.Oneofthemostcommonexamplesofthisiswhencreatingtimerfunctions.
Let'sseethebelowexampleofhowgeneratorscanprovetobeusefulovercallbacks.
Ourexamplewilljustcreateasimpletimedelayfunction.Wewouldthenwanttocallthisfunctionincorporatingadelayof1000,2000and3000ms.
Step1)Defineourcallbackfunctionwiththenecessarytimedelaycode.
CodeExplanation:-
1. HerewearecreatingafunctioncalledTimedelaywithaparametercalledptime.Thiswilltakeinthenecessarytimedelaywewanttointroduceinourapplication.
2. Thenextstepistojustcreateamessage,whichwillbedisplayedtotheusersayingthattheapplicationisgoingtobepauseforthesemanynumbersofmilliseconds.
Step2)Nowlet'slookatthecodeifwewereincorporatingcallbacks.Supposewewantedtoincorporatecallbacksbasedonthevalueof1000,2000and3000milliseconds,thebelowcodeshowshowwewouldneedtoimplementtheseusingcallbacks.
CodeExplanation:-
1. WearecallingtheTimedelayasacallbackwith1000asthevalue.2. NextwewanttocalltheTimedelayfunctionagainwith2000asthevalue.3. Finally,wewanttocalltheTimedelayfunctionagainwith3000asthevalue.
Fromtheabovecode,youcanseethatitbecomesmessieraswewanttostartcallingthefunctionmultipletimes.
Step3)Nowlet'sseehowtoimplementthesamecodeusinggenerators.FromthebelowcodeyoucannowseehowsimpleithasbecometoimplementtheTimedelayfunctionusinggenerators.
CodeExplanation:-
1. WearefirstdefiningageneratorfunctionwhichwillbeusedtocallourTimedelayfunction.
2. WearecallingtheYieldfunctionalongwiththeTimedelayfunctionwith1000astheparametervalue.
3. WearethencallingtheYieldfunctionalongwiththeTimedelayfunctionwith2000astheparametervalue.
4. Finally,wearecallingtheYieldfunctionalongwiththeTimedelayfunctionwith3000astheparametervalue.
FilestreaminNode.jsNodemakesextensiveuseofstreamsasadatatransfermechanism.
Forexample,whenyououtputanythingtotheconsoleusingtheconsole.logfunction,youareactuallyusingastreamtosendthedatatotheconsole.
Node.jsalsohastheabilitytostreamdatafromfilessothattheycanbereadandwrittenappropriately.Wewillnowlookatanexampleofhowwecanusestreamstoreadandwritefromfiles.Weneedtofollowthebelow-mentionedstepsforthisexample
Step1)Createafilecalleddata.txtwhichhasthebelowdata.LetassumethisfileisstoredontheDdriveofourlocalmachine.
TutorialonNode.js
Introduction
Events
Generators
DataConnectivity
UsingJasmine
Step2)Writetherelevantcodewhichwillmakeuseofstreamstoreaddatafromthefile.
varfs=require("fs");
varstream;
stream=fs.createReadStream("D://data.txt");
stream.on("data",function(data){
varchunk=data.toString();
console.log(chunk);
});
CodeExplanation:-
1. Wefirstneedtoincludethe'fs'moduleswhichcontainallthefunctionalityrequiredtocreatestreams.
2. Nextwecreateareadablestreambyusingthemethod–createReadStream.Asaninput,wegivethelocationofourdata.txtfile.
3. Thesteam.onfunctionisaneventhandlerandinit,wearespecifyingthefirstparameteras'data.'Thismeansthatwheneverdatacomesinthestreamfromthefile,thenexecuteacallbackfunction.Inourcase,wearedefiningacallbackfunctionwhichwillcarryout2basicsteps.Thefirstistoconvertthedatareadfromthefileasastring.Thesecondwouldbetosendtheconvertedstringasanoutputtotheconsole.
4. Wearetakingeachchunkofdatawhichisreadfromthedatastreamandconvertingittoastring.
5. Finally,wearesendingtheoutputofeachstringconvertedchunktotheconsole.
Output:
Ifthecodeisexecutedproperly,youwillseetheaboveoutputintheconsole.Thisoutputwillbethesameasthatinthedata.txtfile.
Writingtoafile
Inthesameway,thatwecreateareadstream,wecanalsocreateawritestreamtowritedatatoafile.Let'sfirstcreateanemptyfilewithnocontentscalleddata.txt.Let'sassumethisfileisplacedintheDdriveofourcomputer.
Thebelowcodeshowshowwecanwritedatatothefile.
varfs=require("fs");
varstream;
stream=fs.createWriteStream("D://data.txt");
stream.write("TutorialonNode.js")
stream.write("Introduction")
stream.write("Events")
stream.write("Generators")
stream.write("DataConnectivity")
stream.write("UsingJasmine")
CodeExplanation:-
1. Wearecreatingawritablestreambyusingthemethod–createWriteStream.Asaninput,wegivethelocationofourdata.txtfile.
2. Nextweusedthestream.writeamethodtowritethedifferentlinesoftexttoourtextfile.Thestreamwilltakecareofwritingthisdatatothedata.txtfile.
Ifyouopenthedata.txtfile,youwillnowseethefollowingdatainthefile
TutorialonNode.js
Introduction
Events
Generators
DataConnectivity
UsingJasmine
PipesinNode.jsWithinNodeapplications,streamscanbepipedtogetherusingthepipe()method,whichtakestwoarguments:
ARequiredwritablestreamthatactsasthedestinationforthedataandAnoptionalobjectusedtopassinoptions.
Atypicalexampleofusingpipes,ifyouwanttotransferdatafromonefiletotheother.
Solet'sseeanexampleofhowwecantransferdatafromonefiletotheotherusingpipes.
Step1)Createafilecalleddatainput.txtwhichhasthebelowdata.LetassumethisfileisstoredontheDdriveofourlocalmachine.
TutorialonNode.js
Introduction
Events
Generators
DataConnectivity
UsingJasmine
Step2)CreateablankemptyfilecalleddataOutput.txtandplaceditontheDdriveofyourlocalmachine.
Step3)Writethebelowcodetocarryoutthetransferofdatafromthedatainput.txtfiletothedataOutput.txtfile.
CodeExplanation:-
1. Wearefirstcreatinga"readstream"toourdatainput.txtfilewhichcontainsallourdatawhichneedstobetransferredtothenewfile.
2. Wethenneedtocreatea"writestream"toourdataOutput.txtfile,whichisouremptyfileandisthedestinationforthetransferofdatafromthedatainput.txtfile.
3. Wethenusethepipecommandtotransferthedatafromthereadstreamtothewritestream.Thepipecommandwilltakeallthedatawhichcomesintothereadstream,andpushittothewritestream.
IfyounowopenthedataOutput.txtfile,youwillseeallthedatawhichwaspresentinthedatainput.txtfile.
EventsinNode.jsEventsareoneofthekeyconceptsinNode.jsandsometimesNode.jsisreferredtoasanEvent-drivenframework.
Basically,aneventissomethingthathappens.Forexample,ifaconnectionisestablishedtoadatabase,thenthedatabaseconnectioneventistriggered.Eventdrivenprogrammingistocreatefunctionsthatwillbetriggeredwhenspecificeventsaretriggered.
Let'slookatabasicexampleofdefininganeventinNode.js.
Wearegoingtocreateaneventcalled'data_received'.Whenthiseventistriggered,thetext"datareceived"willbesenttotheconsole.
varevents=require('events');
vareventEmitter=newevents.EventEmitter();
eventEmitter.on('data_received',function(){
console.log('datareceivedsuccesfully.');
});
eventEmitter.emit('data_received');
CodeExplanation:-
1. Usetherequirefunctiontoincludethe'events'module.Withthismodule,youwillbeabletocreateeventsinNode.js.
2. Createaneweventsemitter.Thisisusedtobindtheevent,whichinourcaseis"data_received"toacallbackfunctionwhichisdefinedinstep3.
3. Wedefineanevent-drivenfunctionwhichsaysthatifincasethe"data_received"eventistriggeredthenweshouldoutputthetext"data_received"totheconsole.
4. Finally,wedohaveamanualtriggerofoureventusingtheeventEmiter.emitfunction.Thiswilltriggerthedata_receivedevent.
Whentheprogramisrun,thetext"datareceived"willbesenttotheconsoleasshownbelow.
EmittingEventsWhendefiningevents,therearedifferentmethodsforeventswhichcanbeinvoked.Thistopicfocusesonlookingateachoneofthemindetail.
1. Onetimeeventhandlers
Sometimesyoumaybeinterestedinreactingtoaneventonlythefirsttimeitoccurs.Inthesesituations,youcanusetheonce()method.
Let'sseehowwecanmakeuseoftheoncemethodforeventhandlers.
CodeExplanation:-
1. Hereweareusingthe'once'methodtosaythatfortheevent'data_received,'thecallbackfunctionshouldonlybeexecutedonce.
2. Herewearemanuallytriggeringthe'data_received'event.3. Whenthe'data_received'eventistriggeredagain,thistime,nothingwillhappen.Thisis
becauseofthefirststepwherewesaidthattheeventcouldonlybetriggeredonce.
Ifthecodeisexecutedproperly,theoutputinthelogwillbe'data_receivedsuccessfully'.Thismessagewillonlyappearonceintheconsole.
2. InspectingEventListeners
Atanypointinitslifetime,aneventemittercanhavezeroormorelistenersattachedtoit.Thelistenersforeacheventtypecanbeinspectedinseveralways.
Ifyouareinterestedinonlydeterminingthenumberofattachedlisteners,thenlooknofurtherthantheEventEmitter.listenerCount()method.
(Note:Listenersareimportantbecausethemainprogramshouldknowiflistenersarebeingaddedontheflytoanevent,elsetheprogramwillmalfunctionbecauseadditionallistenerswillgetcalled.)
CodeExplanation:-
1. WearedefininganeventEmittertypewhichisrequiredforusingtheevent-relatedmethods.
2. Wearethendefininganobjectcalledemitterwhichwillbeusedtodefineoureventhandlers.
3. Wearecreating2eventshandlerswhichbasicallydonothing.ThisiskeptsimpleforourexamplejusttoshowhowthelistenerCountmethodworks.
4. NowwhenyouinvokethelistenerCountmethodonourdata_receivedevent,itwillsendthenumberofeventlistenersattachedtothiseventintheconsolelog.
Ifthecodeisexecutedproperly,thevalueof2willbeshownintheconsolelog.
3. ThenewListenerEvent
Eachtimeaneweventhandlerisregistered,theeventemitteremitsanewListenerevent.Thiseventisusedtodetectneweventhandlers.YoutypicallyusenewListenereventwhenyouneedtoallocateresourcesorperformsomeactionforeachneweventhandler.
varevents=require('events');
vareventEmitter=events.EventEmitter;
varemitter=neweventEmitter();
emitter.on("newListener",function(eventName,listener){
console.log("Addedlistenerfor"+eventName+"events");
});
emitter.on('data_received',function(){});
emitter.on('data_received',function(){});
CodeExplanation:-
1. Wearecreatinganeweventhandlerforthe'newListener'event.Sowheneveraneweventhandlerisregistered,thetext"Addedlistenerfor"+theeventnamewillbedisplayedintheconsole.
2. Herewearewritingtotheconsolethetext"Addedlistenerfor"+theeventnameforeacheventregistered.
3. Wearedefining2eventhandlersforourevent'data_received'.
Iftheabovecodeisexecutedproperly,thebelowtextwillbeshownintheconsole.Itjustshowsthatthe'newListener'eventhandlerwastriggeredtwice.
Addedlistenerfordata_receivedevents
Addedlistenerfordata_receivedevents
Summary
UsingcallbackfunctionsinNode.jsdoeshaveitsdisadvantages.Sometimesduringtheprocessofdevelopment,thenesteduseofcallbackfunctionscanmakethecodemessieranddifficulttomaintain.Mostoftheissueswithnestedcallbackfunctionscanbemitigatedwiththeuseofpromisesandgeneratorsinnode.jsAPromiseisavaluereturnedbyanasynchronousfunctiontoindicatethecompletionoftheprocessingcarriedoutbytheasynchronousfunction.Promisescanbenestedwithineachothertomakecodelookbetterandeasiertomaintainwhenmanyasynchronousfunctionneedtobecalledatthesametime.Generatorscanalsobeusedtoalleviatetheproblemswithnestedcallbacksandassistinremovingwhatisknownasthecallbackhell.Generatorsareusedtohalttheprocessingofafunction.Thisisaccomplishedbyusageofthe'yield'methodintheasynchronousfunction.StreamsareusedinNode.jstoreadandwritedatafromInput-Outputdevices.Node.jsmakesuseofthe'fs'librarytocreatereadableandwritablestreamstofiles.Thesestreamscanbeusedtoreadandwritedatafromfiles.
Pipescanbeusedtoconnectmultiplestreamstogether.Oneofthemostcommonexampleistopipethereadandwritestreamtogetherforthetransferofdatafromonefiletotheother.Node.jsisoftenalsotaggedasaneventdrivenframework,andit'sveryeasytodefineeventsinNode.js.Functionscanbedefinedwhichrespondtotheseevents.Eventsalsoexposemethodsforrespondingtokeyevents.Forexample,wehaveseentheonce()eventhandlerwhichcanbeusedtomakesurethatacallbackfunctionisonlyexecutedoncewhenaneventistriggered.
Chapter8:TestingwithJasmine
Testingisakeyelementtoanyapplication.ForNode.js,theframeworkavailablefortestingiscalledJasmine.Inearly2000,therewasaframeworkfortestingjavascriptapplicationscalledJsUnit.Laterthisframeworkgotupgradedandisnowknownasjasmine.
Jasminehelpsinautomatedunittesting,somethingwhichhasbecomequiteakeypracticewhendevelopinganddeployingmoderndaywebapplications.
Inthistutorial,youwilllearnhowtogetyourenvironmentsetupwithjasmineandhowyoucanstarttestingyourfirstNode.jsapplicationwithjasmine.
OverviewofJasminefortestingNode.jsapplicationsJasmineisaBehaviorDrivenDevelopment(BDD)testingframeworkforJavaScript.Itdoesnotrelyonbrowsers,DOM,oranyJavaScriptframework.Thus,it'ssuitedforwebsites,Node.jsprojects,oranywherethatJavaScriptcanrun.TostartusingJasmine,youneedtofirstdownloadandinstallthenecessaryJasminemodules.
Nextyouwouldneedtoinitializeyourenvironmentandinspectthejasmineconfigurationfile.ThebelowstepsshowshowtosetupJasmineinyourenvironment
Step1)InstallingtheNPMModules
TousethejasmineframeworkfromwithinaNodeapplication,thejasminemoduleneedstobeinstalledfirst.Toinstallthejasmine-nodemodule,runthebelowcommand.
npminstalljasmine-node
Step2)Initializingtheproject–Bydoingthis,jasminecreatesaspecdirectoryandconfigurationjsonforyou.Thespecdirectoryisusedtostoreallyourtestfiles.Bydoingthis,jasminewillknowwhereallyourtestsare,andthencanexecutethemaccordingly.TheJSONfileisusedtostorespecificconfigurationinformationaboutjasmine.
Toinitializethejasmineenvironment,runthebelowcommand
jasmineinit
Step3)Inspectyourconfigurationfile.Theconfigurationfilewillbestoredinthespec/supportfolderasjasmine.json.ThisfileenumeratesthesourcefilesandspecfilesyouwouldliketheJasminerunnertoinclude.
Thebelowscreenshotshowsatypicalexampleofthepackage.jsonfileforjasmine.
1. Notethatthespecdirectoryisspecifiedhere.Asnotedearlier,whenjasminerunsitsearchesforalltestsinthisdirectory.
2. Thenextthingtonoteisthespec_filesparameter–Thisdenotesthatwhatevertestfilesarecreatedtheyshouldbeappendedwiththe'spec'keyword.
HowtouseJasminetotestNode.jsapplicationsInordertouseJasminetotestNode.jsapplications,aseriesofstepsneedstobefollowed.
Inourexamplebelow,wearegoingtodefineamodulewhichadd2numberswhichneedtobetested.WewillthendefineaseparatecodefilewiththetestcodeandthenusejasminetotesttheAddfunctionaccordingly.
Step1)Definethecodewhichneedstobetested.Wearegoingtodefineafunctionwhichwilladd2numbersandreturntheresult.Thiscodeisgoingtobewritteninafilecalled"Add.js."
varexports=module.exports={};
exports.AddNumber=function(a,b)
{
returna+b;
};
CodeExplanation:
1. The"exports"keywordisusedtoensurethatthefunctionalitydefinedinthisfilecanactuallybeaccessedbyotherfiles.
2. Wearethendefiningafunctioncalled'AddNumber.'Thisfunctionisdefinedtotake2parameters,aandb.Thefunctionisaddedtothemodule"exports"tomakethefunctionasapublicfunctionthatcanbeaccessedbyotherapplicationmodules.
3. Wearefinallymakingourfunctionreturntheaddedvalueoftheparameters.
Step2)Nextweneedtodefineourjasminetestcodewhichwillbeusedtotestour"Add"functionIntheAdd.jsfile.Thebelowcodeneedstoputinafilecalledadd-spec.js.
Note:-Theword'spec'needstobeaddedtothetestfilesothatitcanbedetectedbyjasmine.
varapp=require("../Add.js");
describe("Addition",function(){
it("Thefunctionshouldadd2numbers",function(){
varvalue=app.AddNumber(5,6);
expect(value).toBe(11);
});
});
CodeExplanation:
1. WeneedtofirstincludeourAdd.jsfilesothatwecantestthe'AddNumber'functioninthisfile.
2. Wearenowcreatingourtestmodule.Thefirstpartofthetestmoduleistodescribeamethodwhichbasicallygivesanameforourtest.Inthiscase,thenameofourtestis"Addition".
3. Thenextbitistogiveadescriptionforourtestusingthe'it'method.4. WenowinvokeourAddnumbermethodandsendin2parameters5and6.Thiswillbe
passedtoourAddnumbermethodintheApp.jsfile.Thereturnvalueisthenstoredinavariablecalledvalue.
5. Thefinalstepistodothecomparisonorouractualtest.SinceweexpectthevaluereturnedbytheAddnumberfunctiontobe11,wedefinethisusingthemethodexpect(value).toBe(theexpectedvalue).
Output
1. Inordertorunthetest,oneneedstorunthecommandjasmine.2. Thebelowscreenshotshowsthatafterthejasminecommandisrun,itwilldetectthat
thereisatestcalledadd-spec.jsandexecutethattestaccordingly.Ifthereareanyerrorsinthetest,itwillbeshownaccordingly.
Summary
InordertotestaNode.jsapplication,thejasmineframeworkneedstobeinstalledfirst.ThisisdonebyusingtheNodepackagemanager.Thetestcodeneedstobewritteninaseparatefile,andtheword'spec'shouldbeappendedtothefilename.Onlyifthisisdonewilljasminebeabletodetectthatafileneedstoberun.Torunthetest,youneedtoexecutethejasminecommand.Thiswillfindallfileswhichhavethe'spec'wordattachedtoitandrunthefileaccordingly.
OneLastThing….
DIDYOUENJOYTHEBOOK?IFSO,THENLETMEKNOWLEAVINGAREVIEWONAMAZON!Reviewsarelifebloodofindependentauthors.Iwouldappreciateevenafewwordsandratingifthat’sallyouhavetimefor
IFYOUDIDNOTLIKETHISBOOK,THENPLEASETELLME!EMAILmeandLetmeknowwhatyoudidn’tlike!PerphaseIcanchangeit.Intoday’sworldabookdoesn’thavetobestagnant,itcanimprovewithtimeandfeedbackfromreaderslikeyou.Youcanimpactthisbook,andIwelcomeyourfeedback.Helpmakethisbookbetterforeveryone!
MoreBooks-
LearnAngularJSin1Day:CompleteAngularJSGuidewithExamples
BUYNOW
LearnMongoDBin1Day:DefinitiveGuidetoMasterMongoDB
BUYNOW
LearnJavain1Day:CompleteBeginnersGuide
BUYNOW
LearnSQLin1Day:DefinitiveGuidetoLearnSQLforBeginners
BUYNOW
LearnPL/SQLin1Day:DefinitiveGuidetoLearnPL/SQLforBeginners
BUYNOW
LearnPythonin1Day:CompletePythonGuidewithExamples
BUYNOW
LearnPHPin1Day:DefinitiveGuidetoLearn&MasterPHPprogramming
BUYNOW
LearnJSPin1Day:DefinitiveGuidetoLearnJSPforBeginners
BUYNOW
LearnASP.Netin1Day:DefinitiveGuidetoLearnASP.NetforBeginners
BUYNOW
LearnSQLitein1Day:DefinitiveGuidetoLearnSQLiteforBeginners
BUYNOW
LearnLinuxin1Day:CompleteLinuxGuidewithExamples
BUYNOW