+ All Categories
Home > Documents > Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for...

Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for...

Date post: 22-Jul-2020
Category:
Upload: others
View: 6 times
Download: 0 times
Share this document with a friend
44
Transcript
Page 1: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO
Page 2: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

LearningNode.jsfor.NETDevelopers

Page 3: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

TableofContents

LearningNode.jsfor.NETDevelopersCreditsAbouttheAuthorAbouttheReviewerwww.PacktPub.com

eBooks,discountoffers,andmoreWhysubscribe?

PrefaceWhatthisbookcoversWhatyouneedforthisbookWhothisbookisforConventionsReaderfeedbackCustomersupport

DownloadingtheexamplecodeDownloadingthecolorimagesofthisbookErrataPiracyQuestions

1.WhyNode.js?WhatisNode.js?

UnderstandingtheNode.jsexecutionmodelNon-blockingEvent-drivenSingle-threaded

IntroducingtheNode.jsecosystemWhyJavaScript?

AclearcanvasFunctionalnatureAbrightfuture

WhentouseNode.jsWritingwebapplicationsIdentifyingotherusecasesWhynow?

Summary2.GettingStartedwithNode.js

InstallingandrunningNode.jsChoosinganeditorUsinganapplicationframework

GettingstartedwithExpressExploringourExpressapplication

Page 4: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

UnderstandingExpressroutesandviewsUsingnodemonforautomaticrestartsCreatingmodularapplicationswithExpressBootstrappinganExpressapplicationUnderstandingExpressmiddleware

ImplementingerrorhandlingUsingExpressmiddleware

Summary3.AJavaScriptPrimer

IntroducingJavaScripttypesJavaScriptprimitivetypes

Functionalobject-orientedprogrammingFunctionalprogramminginJavaScriptUnderstandingscopesinJavaScript

StrictmodeObject-orientedprogramminginJavaScript

ProgrammingwithoutclassesCreatingobjectswiththenewkeyword

ProgrammingwithclassesClass-basedinheritance

Summary4.IntroducingNode.jsModules

OrganizingyourcodebaseJavaScriptmodulesystems

CreatingmodulesinNode.jsDeclaringamodulewithanameanditsownscopeDefiningfunctionalityprovidedbythemoduleImportingamoduleintoanotherscript

Definingadirectory-levelmoduleImplementinganExpressmiddlewaremoduleSummary

5.CreatingDynamicWebsitesHandlinguser-submitteddataCommunicatingviaAjaxImplementingotherdataoperations

ListingdatainviewsIssuingadeleterequestfromtheclientSplittingupExpressviewsusingpartials

Summary6.TestingNode.jsApplications

WritingasimpletestinNode.jsStructuringthecodebasefortestsWritingBDD-styletestswithMocha

Resettingstatebetweentests

Page 5: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

UsingChaiforassertionsCreatingtestdoubles

CreatingtestdoublesusingSinon.JSTestinganExpressapplication

SimplifyingtestsusingSuperAgentFull-stacktestingwithPhantomJSSummary

7.SettingupanAutomatedBuildSettingupanintegrationserver

SettingupapublicGitHubrepositoryBuildingaprojectonTravisCI

AutomatingthebuildprocesswithGulpRunningtestsusingGulp

CheckingcodestylewithESLintAutomaticallyfixingissuesinESLintRunningESLintfromGulp

GatheringcodecoveragestatisticsRunningintegrationtestsfromGulpSummary

8.MasteringAsynchronicityUsingthecallbackpatternforasynchronouscode

ExposingthecallbackpatternConsumingasynchronousinterfaces

WritingcleanerasynchronouscodeusingpromisesImplementingpromise-basedasynchronouscode

ConsumingthepromisepatternParallelisingoperationsusingpromises

CombiningasynchronousprogrammingpatternsSummary

9.PersistingDataIntroducingMongoDB

WhychooseMongoDB?ObjectmodelingJavaScriptScalability

GettingstartedwithMongoDBUsingtheMongoDBshell

UsingMongoDBwithExpressPersistingobjectswithMongooseIsolatingpersistencecodeDependencyinjectioninNode.jsProvidingdependenciesRunningdatabaseintegrationtestsonTravisCI

IntroducingRedis

Page 6: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

WhyuseRedis?InstallingRedisUsingRedisasakey-valuestoreStoringstructureddatainRedis

BuildingauserrankingsystemwithRedisUsingRedisfromNode.js

Testingwithredis-jsImplementinguserrankingswithRedisMakinguseoftheusersservice

AnoteonsecuritySummary

10.CreatingReal-timeWebAppsUnderstandingoptionsforreal-timecommunicationIntroducingSocket.IO

ImplementingachatroomwithSocket.IOScalingreal-timeNode.jsapplications

UsingRedisasabackendIntegratingSocket.IOwithExpressDirectingSocket.IOmessagesTestingSocket.IOapplicationsOrganizingSocket.IOapplications

Exposingreal-timeupdatestothemodelOrganizingSocket.IOapplicationsusingnamespacesPartitioningSocket.IOclientsusingrooms

Summary11.DeployingNode.jsApplications

WorkingwithHerokuSettingupaHerokuaccountandtoolingRunninganapplicationlocallywithHerokuDeployinganapplicationtoHerokuWorkingwithHerokulogs,config,andservices

SettingupMongoDBSettingupRedis

DeployingfromTravisCISettingencryptedTravisCIenvironmentvariables

InstallingRubyCreatinganencryptedenvironmentvariable

FurtherresourcesSummary

12.AuthenticationinNode.jsIntroducingPassport

ChoosinganauthenticationstrategyUnderstandingthird-partyauthentication

UsingExpresssessions

Page 7: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

SpecifyingasessionsecretDecidingwhenthesessiongetssavedUsingalternativesessionstoresUsingsessionmiddleware

ImplementingsocialloginSettingupaTwitterapplicationConfiguringPassportPersistinguserdatawithRedisConfiguringPassportwithpersistenceHidingfunctionalityfromunauthenticatedusersIntegrationtestingwithPassport

AllowinguserstologoutAddingotherloginprovidersSummary

13.CreatingJavaScriptPackagesWritinguniversalmodules

ComparingNode.jsandRequireJSSupportingthebrowserenvironmentUsingAMDmoduleswithRequireJSIsomorphicJavaScript

WritingnpmpackagesDefiningannpmpackage

PublishingapackagetonpmRunningautomatedclientsonthewebReleasingastandalonetooltonpm

UsingNode.jsmodulesinthebrowserControllingBrowserify'soutput

Summary14.Node.jsandBeyond

UnderstandingNode.jsversioningAbriefhistoryofNode.jsIntroducingtheNode.jsLTSschedule

UnderstandingECMAScriptversioningExploringECMAScript2015

UnderstandingES2015modulesUsingsyntaximprovementsfromES2015

Thefor...ofloopThespreadoperatorandrestparametersDestructuringassignment

IntroducinggeneratorsIntroducingECMAScript2016GoingbeyondJavaScript

Exploringcompile-to-JavaScriptlanguagesTypeScript

Page 8: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

CoffeeScriptAndbeyond...

IntroducingatrueassemblylanguageforthewebUnderstandingasm.jsUnderstandingWebAssembly

JavaScriptandASP.NETExploring.NETCore

Definingprojectstructurein.NETCoreManagingdependenciesin.NETCoreBuildingwebapplicationsinASP.NETCore

IntegrationwithJavaScriptServer-sideJavaScriptintegrationwith.NET

SummaryIndex

Page 9: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

LearningNode.jsfor.NETDevelopers

Page 10: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

LearningNode.jsfor.NETDevelopersCopyright©2016PacktPublishing

Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.

Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.

PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.

Firstpublished:June2016

Productionreference:1170616

PublishedbyPacktPublishingLtd.

LiveryPlace

35LiveryStreet

BirminghamB32PB,UK.

ISBN978-1-78528-009-2

www.packtpub.com

Page 11: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

CreditsAuthor

HarryCummings

Reviewer

DavidSimons

CommissioningEditor

KunalParikh

AcquisitionEditor

RahulNair

ContentDevelopmentEditor

TrushaShriyan

TechnicalEditor

JayeshSonawane

CopyEditor

SafisEditing

ProjectCoordinator

KinjalBari

Proofreader

SafisEditing

Indexer

MariammalChettiyar

Graphics

DishaHaria

Page 12: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

ProductionCoordinator

NileshMohite

CoverWork

NileshMohite

Page 13: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

AbouttheAuthorHarryCummingshasbeenworkinginsoftwaredevelopmentfor8years,andforthepastfewyears,hehasperformedtheroleoftechnicalleadacrossavarietyofprojectsforvariedclients.Hehas,inthepast,alsoworkedasadeveloper,projectmanager,andconsultant.Thisgiveshimanexcellentall-roundviewoftheroleofatechnicalleadanditsrelationshipwithotherrolesaswellasinsightintoeverystageofprojectdelivery,frominitialanalysistolong-termmaintenance.

HarryhasextensiveexperienceinC#/.NET,JavaandScala,andJavaScript/Node.js.Hecontinuestoworkdirectlywiththesetechnologiesonaregularbasisintheteamsthatheleads.Hisbroaderinterestsandexpertiselieinsharingandnurturingsoftwaredevelopmentbestpracticesthroughtrainingandmentoring.HehasappearedatconferencessuchasNDCLondonandSDDConf,speakingaboutdiversetopics,rangingfromintroductoryNode.jsthroughtoautomatedteststrategiesandlong-termprojectmaintainability.

Page 14: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

AbouttheReviewerDavidSimonsisaLondon-basedsoftwareconsultant.Heisfamiliarwithawiderangeoftools,havinghelpedclientssuchastheBBCandNewsInternationaldeliverwebsolutionsinarangeoflanguages,including.NET,Java,andfull-stackJavaScript.Heshareshisinsightsaroundtheseandhisbackgroundinstatisticsresearchatarangeofconferences,includingNDCandJSConf.

Asof2016,heworkswithLondon-basedconsultancyGraphAwaretoadvocateandconsultontheuseofgraphdatabasesinmodernapplications.

Page 15: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

www.PacktPub.com

Page 16: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

eBooks,discountoffers,andmoreDidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusat<[email protected]>formoredetails.

Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.

https://www2.packtpub.com/books/subscription/packtlib

DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt'sonlinedigitalbooklibrary.Here,youcansearch,access,andreadPackt'sentirelibraryofbooks.

Page 17: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser

Page 18: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

PrefaceThepurposeofthisbookistohelp.NETorJavadevelopersmaketheleaptoNode.js.Youmayhavesomewebdevelopmentexperience,andperhapsyou'vewrittensomebrowser-basedJavaScriptinthepast.ItmightnotbeobviouswhyanyonewouldwanttotakeJavaScriptoutofthebrowseranduseitforserver-sidedevelopment.However,thisisexactlywhatNode.jsdoes.What'smore,Node.jshasbeenaroundforlongenoughnowtohavematuredasaplatform,andhassustaineditsimpressivegrowthinpopularitywellbeyondanyperiodthatcouldbeattributedtoinitialhypeoveranewtechnology.

ThefirstobjectiveofthisbookthenistoexplainwhyNode.jsisacompellingtechnologythat'sworthlearningmoreabout.ThefirstfewchaptersintroduceNode.jswiththisinmind,quicklygetyouupandrunningwithNode.js,andprovideanimportant(re)introductiontotheJavaScriptlanguagetosetyouontherighttrack.

ThemainpartofthisbookwillthentakeyouthroughaworkedexampleofbuildingupaNode.jsweb-applicationstepbystep.Intheprocess,we'llillustratealltheimportanttoolsandtechniquesrequiredforreal-worlddevelopmentprojectsinNode.js.TheaimistomakethemostofyourexistingdevelopmentexpertisetoallowyoutoquicklyreachthesamelevelofbestpracticesandprofessionalismwithNode.js.

ThefinalchaptersofthebookshowhowtouseNode.jsforotherpurposesoutsideofwebapplicationsandhowtocontinuelearningNode.jsandexploringtheecosystemaroundit.We'llalsoseehowyoucanuseNode.jsalongside.NETandbenefitfromapplyingyourprogrammingskillsacrossbothtechnologies.

Page 19: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

WhatthisbookcoversChapter1,WhyNode.js?,introducesNode.jsasaprogrammingplatform.ItcoverstheexecutionmodelofNode.js,particularlyhowitdiffersfrom.NETandJava,andtheusecasesinwhichthesedifferencesbecomestrengths.ThischapteralsodiscussesthesuitabilityofJavaScriptasadevelopmentlanguage.

Chapter2,GettingStartedwithNode.js,divesstraightintocreatingaNode.jsapplication.Inthischapter,youwillinstallNode.js,chooseacodeeditor,andsetupaminimalwebapplicationproject.You'llalsolearnsomeimportantcommand-linetoolsforworkingwithNode.js.

Chapter3,AJavaScriptPrimer,introducesthemostimportantthingstoknowwhenprogramminginJavaScript.ItdescribestheJavaScripttypesystemanditsparticularflavoroffunctionalobject-orientedprogramming,includingprototype-basedinheritance.ThischapteralsocoversafewkeygotchasandJavaScriptlanguagequirks.

Chapter4,IntroducingNode.jsModules,explainshowtostructureJavaScriptapplicationsusingmodules.ItintroducestheNode.jsmodulesystemandshowsyouhowtousethistoorganiseyourapplication'scode.

Chapter5,CreatingDynamicWebsites,expandsontheexamplesfromthepreviouschaptertobuildafunctioningwebapplication.You'lladdaJSONAPIanddynamicviewstoyourapplicationandcommunicatebetweentheclientandserverusingAjax.

Chapter6,TestingNode.jsApplications,showsyouhowtowriteautomatedtestsinJavaScriptandNode.js.ItintroducesanumberoftoolsandlibrariesforwritingandrunningtestsinJavaScript,andguidesyouthroughwritingavarietyofunittestsandintegrationtestsforyourapplication.

Chapter7,SettingupanAutomatedBuild,coversbuildautomationandcontinuousintegrationinNode.js.You'llsetupaCIserverandtaskrunnerforyourapplication,addingautomatedtaskstoruntests,executestaticanalysis,andassesscodecoverage.

Chapter8,MasteringAsynchronicity,introducesdifferentpatternsforasynchronousprogramminginJavaScript.You'llapplythesetoyourownapplicationandmakethemostofJavaScriptlanguagefeaturesandlibrariesforsimplifyingasynchronouscode.

Chapter9,PersistingData,explainspersistentdatastoresthatcanbeusedwithNode.js.ItintroducesMongoDBandRedis,explainingtheirdifferentdatamodelsandtheirusecases.You'llintegratebothofthesedatastoreswithyourNode.jsapplication.

Chapter10,CreatingReal-timeWebApps,showshowtoimplementreal-timetwo-waycommunicationbetweentheclientandtheserver.You'llusetheSocket.IOlibrarytoaddreal-timefunctionalityintoyourapplication.You'llalsoseehowtowritetestsforthisfunctionalityand

Page 20: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

howtowritescalablereal-timeapplicationsusingRedisasabackend.

Chapter11,DeployingNode.jsApplications,demonstrateshowtogetaNode.jsapplicationontotheWeb.You'lldeployyourapplicationtoafreecloud-hostingprovider.You'llseehowtoconfiguredatastoresandhowtouseremoteserverlogsfordebugging.

Chapter12,AuthenticationinNode.js,coversauthenticationforNode.jswebapplications.You'llimplementauthenticationusingthird-partyproviders,integratethiswithyourapplication,andshowdifferentcontenttologged-inandlogged-outusers.

Chapter13,CreatingJavaScriptPackages,explainshowtocreatestandaloneJavaScriptpackagesforusebyothers.You'llseehowtowriteuniversalJavaScriptlibrariesthatcanrunonboththeclientandtheserver,andhowtowriteastandalonecommand-lineapplicationusingNode.js.

Chapter14,Node.jsandBeyond,putsthecontentofthisbookinawidercontext.ItexplainshowNode.jsandJavaScriptarecontinuingtoevolve,soyoucanbepreparedforandtakeadvantageofupcomingchanges.ItcoverssomealternativeprogramminglanguagesforNode.jsandtheWeb,andhowtheserelatetoJavaScript.ItdiscusseshowsomeoftheprinciplesfromNode.jscanbeappliedto.NETprogramming,andillustrateshowtheseareparticularlyvisiblein.NETCore(thenewversionof.NET).ItalsoshowshowyoucanuseNode.jstogetherwith.NETtogainthebestofbothworlds.

Page 21: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

WhatyouneedforthisbookAllofthetoolsandservicesusedinthisbookareavailableforfreeonline.Mostoftheworkedexamplesrequireanactivewebconnectionatsomepoint.Togetstarted,youneednothingmorethanaconsole,awebbrowser,andpermissiontoinstallnewsoftwareonyourmachine.Tosupportdeveloperscomingfroma.NETbackground,someoftheconsolelistingsorexamplestepsinthisbookuseWindowsconventions(forexample,backslashesinpaths).NoneoftheexamplesdependonWindowsspecificallythough.YoucanworkthroughthisbookonWindows,MacOSX,orLinux.

Page 22: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

WhothisbookisforThisbookisfor.NETorJavadeveloperswhoareinterestedinlearningNode.js.NopriorexperiencewithNode.jsisexpected.Youmighthavewrittensomeclient-sideJavaScriptbefore,butthisisnotrequired.ThemainworkedexampleinthisbookisaNode.jswebapplication.Webdevelopmentexperiencein.NETorJavawillbehelpful,butit'snotnecessarytohaveexperiencewithanyparticularapplicationlibraryorframework.

Page 23: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

ConventionsInthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestylesandanexplanationoftheirmeaning.

Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:"ES2015introducestheletkeywordfordeclaringvariables."

Ablockofcodeissetasfollows:

<!DOCTYPEhtml>

<html>

<head>

<title>{{title}}</title>

<linkrel='stylesheet'href='/stylesheets/style.css'/>

</head>

<body>

<h1>{{title}}</h1>

<p>Welcometo{{title}}</p>

</body>

</html>

Whenwewishtodrawyourattentiontoaparticularpartofacodeblock,therelevantlinesoritemsaresetinbold:

/*GEThomepage.*/

router.get('/',function(req,res,next){

res.render('index',{title:'Express',name:'World'});

});

Anycommand-lineinputoroutputiswrittenasfollows:

>npminstall–gnodemon

Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,forexample,inmenusordialogboxes,appearinthetextlikethis:"ClickingtheNextbuttonmovesyoutothenextscreen."

Note

Warningsorimportantnotesappearinaboxlikethis.

Tip

Tipsandtricksappearlikethis.

Page 24: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsusdeveloptitlesthatyouwillreallygetthemostoutof.

Tosendusgeneralfeedback,simplye-mail<[email protected]>,andmentionthebook'stitleinthesubjectofyourmessage.

Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideatwww.packtpub.com/authors.

Page 25: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.

Page 26: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

DownloadingtheexamplecodeYoucandownloadtheexamplecodefilesforthisbookfromhttps://github.com/NodeJsForDevelopersandalsofromyouraccountathttp://www.packtpub.com.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.

Youcandownloadthecodefilesbyfollowingthesesteps:

1. Loginorregistertoourwebsiteusingyoure-mailaddressandpassword.2. HoverthemousepointerontheSUPPORTtabatthetop.3. ClickonCodeDownloads&Errata.4. EnterthenameofthebookintheSearchbox.5. Selectthebookforwhichyou'relookingtodownloadthecodefiles.6. Choosefromthedrop-downmenuwhereyoupurchasedthisbookfrom.7. ClickonCodeDownload.

YoucanalsodownloadthecodefilesbyclickingontheCodeFilesbuttononthebook'swebpageatthePacktPublishingwebsite.Thispagecanbeaccessedbyenteringthebook'snameintheSearchbox.PleasenotethatyouneedtobeloggedintoyourPacktaccount.

Oncethefileisdownloaded,pleasemakesurethatyouunziporextractthefolderusingthelatestversionof:

WinRAR/7-ZipforWindowsZipeg/iZip/UnRarXforMac7-Zip/PeaZipforLinux

Page 27: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

DownloadingthecolorimagesofthisbookWealsoprovideyouwithaPDFfilethathascolorimagesofthescreenshots/diagramsusedinthisbook.Thecolorimageswillhelpyoubetterunderstandthechangesintheoutput.Youcandownloadthisfilefromhttp://www.packtpub.com/sites/default/files/downloads/LearningNodejsForNETDevelopers_ColorImages.pdf

Page 28: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

ErrataAlthoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthecode—wewouldbegratefulifyoucouldreportthistous.Bydoingso,youcansaveotherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/submit-errata,selectingyourbook,clickingontheErrataSubmissionFormlink,andenteringthedetailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedandtheerratawillbeuploadedtoourwebsiteoraddedtoanylistofexistingerrataundertheErratasectionofthattitle.

Toviewthepreviouslysubmittederrata,gotohttps://www.packtpub.com/books/content/supportandenterthenameofthebookinthesearchfield.TherequiredinformationwillappearundertheErratasection.

Page 29: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

PiracyPiracyofcopyrightedmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.IfyoucomeacrossanyillegalcopiesofourworksinanyformontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.

Pleasecontactusat<[email protected]>withalinktothesuspectedpiratedmaterial.

Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluablecontent.

Page 30: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

QuestionsIfyouhaveaproblemwithanyaspectofthisbook,youcancontactusat<[email protected]>,andwewilldoourbesttoaddresstheproblem.

Page 31: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

Chapter1.WhyNode.js?Node.jsisstillrelativelynewcomparedtoplatformssuchas.NETandJava,buthasbecomeverypopularinashorttime,andhasevenstartedinfluencingtheseplatforms.Thisisthankstoitsdistinctiveprogrammingmodel,extensiveecosystem,andpowerfultooling.

ThesefactorsmakeNode.jsacompellingalternativetootherplatforms.Theycanalsomakeitintimidating.Itsdistinctiveprogrammingmodelmayseemquitealiencomparedtootherplatforms.Thesheerrangeofavailablelibrariesandtoolscanbebewildering.

ThisbookwillguideyouthroughNode.jssoyoucanstartusingitinyourapplications.ItwillhelpyoutounderstandNode.js,navigateitsecosystem,andleverageyourexistingdevelopmentskillsinthisnewenvironment.

Inthischapter,wewillcoverthefollowingtopics:

IntroducingtheNode.jsplatformSeeinghowitsexecutionmodelworksExploringtheNode.jsecosystemLookingatJavaScriptasalanguagechoiceConsideringtherangeofusecasesforNode.js

Page 32: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

WhatisNode.js?Node.jsconsistsofaJavaScriptenginetogetherwithlow-levelAPIsforcoreserver-sidefunctionality.TheexecutionengineisthesameV8enginedevelopedfortheChromewebbrowser.Node.jstakesthisengineandembedsitinastandaloneapplicationthatcanrunJavaScriptoutsidethebrowser.

InNode.js,thestandardAPIsfoundinbrowserstosupportclient-sidewebdevelopment,suchastheDocumentObjectModel(DOM)andXMLHttpRequest,arenotpresent.Instead,thereareAPIstosupportgeneral-purposeapplicationdevelopment.ThesecoreAPIscoverlow-levelfunctionalitysuchasthefollowing:

NetworkingandsecurityAccessingthefilesystemDefiningandrequiringmodulesRaisingandconsumingeventsHandlingbinarydatastreamsCompressionUTF-8supportRetrievingbasicinformationabouttheOSManagingchildprocesses

SomeoftheseAPIsmayalreadybefamiliarfromdevelopingclient-sideJavaScript.Forexample,theTimersAPIexposesthefamiliarsetTimeoutandsetIntervalfunctions.

Node.jsalsoprovidesseveraltoolstohelpwiththedevelopmentprocess.Theseincludeconsolelogging,debugging,aRead-Eval-PrintLoop(REPL)(orinteractiveconsole),andbasicassertionsfortesting.

Page 33: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

UnderstandingtheNode.jsexecutionmodelTheexecutionmodelofNode.jsfollowsthatofJavaScriptinthebrowser.Itisquitedifferentfromthatofmostgeneral-purposeprogrammingplatforms.

Statedformally,Node.jshasasingle-threaded,non-blocking,event-drivenexecutionmodel.Wewilldefineeachofthesetermsinthissection.

Non-blocking

Putsimply,Node.jsrecognizesthatmanyprogrammesspendmostoftheirtimewaitingforotherthingstohappen,forexample,slowI/Ooperationssuchasdiskaccessandnetworkrequests.

Node.jsaddressesthisbymakingtheseoperationsnon-blocking.Thismeansthatprogramexecutioncancontinuewhiletheyhappen.Forexample,thefilesystemAPI'sstatfunctionforretrievingstatisticsaboutafilemaybecalledasfollows:

fs.stat('/hello/world',function(error,stats){

console.log('Filelastupdatedat:'+stats.mtime);

});

Twoargumentsarepassedtothefs.statfunction:thenameofthefilethatweareinterestedin,andacallbackfunction.Thefs.statcallreturnsimmediately,returningcontrolofexecutiontothecurrentthreadbutnotreturningavalue.Iftherearefurthercommandsfollowingthefs.statcall,thesewillthenbeexecuted.Otherwise,thethreadisreleasedtoperformotherwork.Thecallbackfunctionisinvoked(thatis'calledback')onlyaftertheruntimehasfinishedcommunicatingwiththefilesystem.Theresultofthefilesystemoperationispassedintothecallbackfunction.

Thisnon-blockingapproachisalsocalledasynchronousprogramming.Otherplatformssupportthis(forexample,C#'sasync/awaitkeywordsand.NET'sTaskParallelLibrary).However,itisbakedintoNode.jsinawaythatmakesitsimpleandnaturaltouse.AsynchronousAPImethodsareallcalledinthesamewayasfs.stat.Theyalltakeacallbackfunctionthatgetspassederrorandresultarguments.

Event-driven

Theevent-drivennatureofNode.jsdescribeshowoperationsarescheduled.Intypicalproceduralenvironments,aprogramhasanentrypointthatexecutesasetofcommandsuntilcompletion,orentersaloopandperformssomeprocessingoneachiteration.

Node.jshasabuilt-ineventloop,whichisn'texposedtothedeveloper.Itisthejoboftheeventlooptodecidewhichpieceofcodetoexecutenext.Typically,thiswillbeacallbackfunctionthatisreadytoruninresponsetosomeotherevent.Forexample,afilesystemoperationmayhavecompleted,atimeoutmayhaveexpired,oranewnetworkrequestmayhavearrived.

Thisbuilt-ineventloopsimplifiesasynchronousprogrammingbyprovidingaconsistentapproach

Page 34: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

andavoidingtheneedforapplicationstomanagetheirownscheduling.

Single-threaded

Thesingle-threadednatureofNode.jssimplymeansthatthereisonlyonethreadofexecutionineachprocess.Also,eachpieceofcodeisguaranteedtoruntocompletionwithoutbeinginterruptedbyotheroperations.Thisgreatlysimplifiesdevelopmentandmakesprogramseasiertoreasonabout.Itremovesthepossibilityforarangeofconcurrencyissues.Forexample,itisnotnecessarytosynchronize/lockaccesstosharedin-processstateasitisinJavaor.NET.Aprocesscan'tdeadlockitselforcreateraceconditionswithinitsowncode.Single-threadedprogrammingisonlyfeasibleifthethreadnevergetsblockedwaitingforlong-runningworktocomplete.Thus,thissimplifiedprogrammingmodelismadepossiblebythenon-blockingnatureofNode.js.

Page 35: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

IntroducingtheNode.jsecosystemThebuilt-inNode.jsAPIsprovidealow-levelcoreforcreatingapplications.ApplicationstypicallyonlyuseasmallnumberoftheseAPIsdirectly.Theyoftenusethird-partylibrarymodulesthatprovidehigher-levelabstractionsforapplicationdevelopment.

Node.jshasitsownpackagemanager,npm.Thisissimilarto.NET'sNuGetorthepackagemanagementaspectsofJava'sMaven.ApplicationsspecifytheirdependenciesinasimpleJSONfile.

Thenpmregistryprovidesacentralrepositoryforpackages.Thisregistryhasgrownrapidlyandisalreadymuchlarger(intermsofnumberofavailablepackages)thanthecorrespondingrepositoriesforotherplatforms(seehttp://www.modulecounts.com/).Therearehundredsofthousandsofpackagesavailable,providingavastarrayoffunctionality.

Thenpmcommandlinetoolcanbeusedtodownloadpackagesandinstallnewones.Librarydependenciesareinstalledlocallytoeachapplication.Somepackagesprovidecommand-linetools,whichmaybeinstalledgloballyratherthanunderaspecificproject.

Manyframeworksavailableonnpmaresplitintoasmallextensiblecoreandanumberofcomposablemodules.Thisapproachmakesiteasytounderstandthelibrariesonwhichyourapplicationdepends,avoidingtheneedtoreasonaboutcomplexheavyweightframeworks.

Theconsistencyofcallingnon-blocking(asynchronous)APImethodsinNode.jscarriesthroughtoitsthird-partylibraries.Thisconsistencymakesiteasytobuildapplicationsthatareasynchronousthroughout.

Page 36: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

WhyJavaScript?JavaScriptisalanguagethatcanseemunintuitivecomparedtootherpopularobject-oriented(OO)languages.Italsohasanumberofquirksandflawsthathavedrawncriticism(andoccasionalridicule).Itmightthenseemasurprisingchoiceoflanguageforanewprogrammingplatform.ThissectiondiscussesthefactorsthatmakeJavaScriptamoreappealingchoice.

Page 37: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

AclearcanvasThesizeandcomplexityofJavaScriptispartofitsappeal.Thecorelanguageitself,whichdoesn'tincludeAPIssuchastheDOM,issmallandsimple.ThismakesiteasyforNode.jstoestablishitsownstylesandconventions.

ThenewAPIsprovidedbyNode.jsandtheconsistentapproachtoasynchronousprogrammingwouldn'tbepossibleinamorecomplexlanguagewithalargerpre-existingstandardclasslibrary.

Page 38: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

FunctionalnatureJavaScriptwasfirstbuiltasaprogramminglanguageforclient-sidefunctionalityinthebrowser.Thismightnotmakeitanobviouschoiceforgeneral-purposeprogramming.

Infact,thesetwousecasesdohavesomethingimportantincommon.Userinterfacecodeisnaturallyevent-driven(forexample,bindingeventhandlerstobuttonclicks).Node.jsmakesthisavirtuebyapplyinganevent-drivenapproachtogeneral-purposeprogramming.

JavaScriptsupportsfunctionsasfirst-classobjects.Thismeansit'seasytocreatefunctionsdynamicallyandpassaroundreferencestothem.Thisfitsinwellwiththeasynchronous,non-blockingapproachofNode.js.Inparticular,it'seasytoexposeanduseAPIsbasedaroundcallbackfunctions.

Page 39: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

AbrightfutureJavaScripthasreceivedalotofattentioninthelastseveralyearsasithasbecomemorewidelyusedforprovidingrichfunctionalityontheWeb.BrowservendorshaveputahugeamountofengineeringeffortintoimprovingtheperformanceofJavaScript.Node.jsbenefitsfromthisdirectlyviaitsuseofChrome'sV8engine.

TheJavaScriptlanguageitselfisundergoingsomemajorchangesforthebetter.TheECMAScript2015standard(previouslyknownasES6)representsthemostsignificantrevisionofthelanguageinitshistory.Itintroducesfeaturesthatmakethelanguagemoreintuitiveandlessverbose.ItalsoaddressesflawsthatJavaScripthasbeencriticizedforinthepast,removinggotchasandmakingprogramseasiertoreasonabout.

Page 40: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

WhentouseNode.jsAsdiscussedearlierinthischapter,Node.jsrecognizesthatI/Oisabottleneckformanyapplications.Onmostprogrammingplatforms,threadswillwastetimeblockingonI/Ooperations.Thereareapproachesdeveloperscantaketoavoidthis,buttheseallinvolveaddingsomecomplexitytotheircode.InNode.js,theplatformitselfprovidesacompletelynaturalapproach.

Page 41: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

WritingwebapplicationsTheflagshipusecaseforNode.jsisbuildingwebapplications.Theseareinherentlyevent-drivenasmostorallprocessingtakesplaceinresponsetoHTTPrequests.Also,manywebsitesdolittlecomputationalheavy-liftingoftheirown.TheytendtoperformalotofI/Ooperations:

StreamingrequestsfromtheclientTalkingtoadatabase,locallyoroverthenetworkPullingindatafromremoteAPIsoverthenetworkReadingfilesfromdisktosendbacktotheclient

ThesefactorsmakeI/Ooperationsalikelybottleneckforwebapplications.Thenon-blockingprogrammingmodelofNode.jsallowswebapplicationstomakethemostofasinglethread.AssoonasanyoftheseI/Ooperationsstarts,thethreadisimmediatelyfreetopickupandstartprocessinganotherrequest.ProcessingofeachrequestcontinuesviaasynchronouscallbackswhenI/Ooperationscomplete.Theprocessingthreadisonlykickingoffandlinkingtogethertheseoperations,neverwaitingforthemtocomplete.ThisallowsNode.jstohandleamuchhigherrateofrequestsperthreadthanotherplatforms.Youcanalsostillmakeuseofmultiplethreads(forexample,onmulti-coreCPUs)bysimplyrunningmultipleinstancesoftheNode.jsprocess.

Page 42: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

IdentifyingotherusecasesThereareofcoursesomeapplicationsthatdon'tperformmuchI/OandaremorelikelytobeCPUbound.Node.jswouldbelesssuitableforcomputationally-intensiveapplications.Programsthatdoalotofprocessingofin-memorydataarelessconcernedaboutI/O.

WebapplicationsarenottheonlyI/O-heavyapplicationsthough.OtherclassesofprogramthatcouldbeagoodcandidateforNode.jsincludethefollowing:

ToolsthatmanipulatelargeamountsofdataondiskSupervisorprogramscoordinatingothersoftwareorhardwareNon-browserGUIapplicationsthatneedtorespondtouserinput

Node.jsisespeciallysuitableforglueapplicationsthatpulltogetherfunctionalityfromotherremoteservices.Theincreasingpopularityofmicroservicesasanarchitecturalpatternmakesthiskindofapplicationmorecommon.

Page 43: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

Whynow?Node.jshasbeenaroundforseveralyears,butnowistheperfecttimetostartusingitifyouhaven'talready.

ThereleaseofNode.jsv4towardstheendof2015consolidatedtheproject'sgovernancemodelandheraldsNode.jscomingtomaturity.ItalsoallowstheprojecttokeepmoreuptodatewiththeV8engine.ThismeansthatNode.jscanbenefitmoredirectlyfromongoingdevelopmentonV8.Forexample,securityandperformanceimprovementstoV8willnowmaketheirwayintoNode.jsmuchsooner.

Asdiscussedearlierinthischapter,thereleaseoftheECMAScript2015standardmakesJavaScriptamuchmoreappealinglanguage.ItpullsinusefulfeaturesfromotherpopularOOlanguagesandresolvesanumberoflong-standingflawsinJavaScript.

Meanwhile,theecosystemofthirdpartylibrariesandtoolsaroundNode.jsandJavaScriptcontinuestogrow.Node.jsistreatedasafirst-classcitizenbymajorhostingplatforms.CompaniessuchasGoogleandMicrosoftarealsothrowingtheirweightbehindJavaScriptandrelatedtechnologies.

Page 44: Learning Node.js for .NET Developers · 10. Creating Real-time Web Apps Understanding options for real-time communication Introducing Socket.IO Implementing a chat room with Socket.IO

SummaryInthischapter,wehaveunderstoodNode.jsanditsdistinctiveexecutionmodel,exploredthegrowingecosystemaroundNode.jsandJavaScript,seenthereasonsforJavaScriptasalanguagechoice,anddescribedthekindsofapplicationthatcanbenefitfromNode.js.

NowthatyouknowhowNode.jsworksandwhentouseit,it'stimetodiveinandgetourfirstNode.jsapplicationupandrunning.


Recommended