The Node Beginner BookWord文档下载推荐.docx
《The Node Beginner BookWord文档下载推荐.docx》由会员分享,可在线阅读,更多相关《The Node Beginner BookWord文档下载推荐.docx(38页珍藏版)》请在冰豆网上搜索。
Which,ofcourse,isnotexactlyworld-changing,butwewillgosomeextramilesandnotonlycreatethecodethatis"
justenough"
tomaketheseusecasespossible,butcreateasimple,yetcompleteframeworktocleanlyseparatethedifferentaspectsofourapplication.YouwillseewhatImeaninaminute.
WewillstartwithlookingathowJavaScriptdevelopmentinNode.jsisdifferentfromJavaScriptdevelopmentinabrowser.
Next,wewillstaywiththegoodoldtraditionofwritinga"
application,whichisamostbasicNode.jsapplicationthat"
does"
something.
Then,wewilldiscusswhatkindof"
real"
applicationwewanttobuild,dissectthedifferentpartswhichneedtobeimplementedtoassemblethisapplication,andstartworkingoneachofthesepartsstep-by-step.
Aspromised,alongthewaywewilllearnaboutsomeofthemoreadvancedconceptsofJavaScript,howtomakeuseofthem,andlookatwhyitmakessensetousetheseconceptsinsteadofthoseweknowfromotherprogramminglanguages.
Thesourcecodeofthefinishedapplicationisavailablethrough
theNodeBeginnerBookGithubrepository.
Tableofcontents
∙About
oStatus
oIntendedaudience
oStructureofthisdocument
∙JavaScriptandNode.js
oJavaScriptandYou
oAwordofwarning
oServer-sideJavaScript
o"
∙AfullblownwebapplicationwithNode.js
oTheusecases
oTheapplicationstack
∙Buildingtheapplicationstack
oAbasicHTTPserver
oAnalyzingourHTTPserver
oPassingfunctionsaround
oHowfunctionpassingmakesourHTTPserverwork
oEvent-drivencallbacks
oHowourserverhandlesrequests
oFindingaplaceforourservermodule
oWhat'
sneededto"
route"
requests?
oExecutioninthekingdomofverbs
oRoutingtorealrequesthandlers
oMakingtherequesthandlersrespond
▪Howtonotdoit
▪Blockingandnon-blocking
▪Respondingrequesthandlerswithnon-blockingoperations
oServingsomethinguseful
▪HandlingPOSTrequests
▪Handlingfileuploads
oConclusionandoutlook
JavaScriptandNode.js
JavaScriptandYou
Beforewetalkaboutallthetechnicalstuff,let'
stakeamomentandtalkaboutyouandyourrelationshipwithJavaScript.Thischapterisheretoallowyoutoestimateifreadingthisdocumentanyfurthermakessenseforyou.
Ifyouarelikeme,youstartedwithHTML"
development"
longago,bywritingHTMLdocuments.YoucamealongthisfunnythingcalledJavaScript,butyouonlyuseditinaverybasicway,addinginteractivitytoyourwebpageseverynowandthen.
Whatyoureallywantedwas"
therealthing"
youwantedtoknowhowtobuildcomplexwebsites-youlearnedaprogramminglanguagelikePHP,Ruby,Java,andstartedwriting"
backend"
code.
Nevertheless,youkeptaneyeonJavaScript,yousawthatwiththeintroductionofjQuery,Prototypeandthelikes,thingsgotmoreadvancedinJavaScriptland,andthatthislanguagereallywasaboutmorethan
window.open().
However,thiswasallstillfrontendstuff,andalthoughitwasnicetohavejQueryatyourdisposalwheneveryoufeltlikespicingupawebpage,attheendofthedayyouwere,atbest,aJavaScript
user,butnotaJavaScript
developer.
AndthencameNode.js.JavaScriptontheserver,howcoolisthat?
Youdecidedthatit'
sabouttimetocheckouttheold,newJavaScript.Butwait,writingNode.jsapplicationsistheonething;
understandingwhytheyneedtobewrittenthewaytheyarewrittenmeans-understandingJavaScript.Andthistimeforreal.
Hereistheproblem:
BecauseJavaScriptreallylivestwo,maybeeventhreelives(thefunnylittleDHMTLhelperfromthemid-90'
s,themoreseriousfrontendstufflikejQueryandthelikes,andnowserver-side),it'
snotthateasytofindinformationthathelpsyoutolearnJavaScriptthe"
right"
way,inordertowriteNode.jsapplicationsinafashionthatmakesyoufeelyouarenotjustusingJavaScript,youareactuallydevelopingit.
Becausethat'
sthecatch:
youalreadyareanexperienceddeveloper,youdon'
twanttolearnanewtechniquebyjusthackingaroundandmis-usingit;
youwanttobesurethatyouareapproachingitfromtherightangle.
Thereis,ofcourse,excellentdocumentationoutthere.Butdocumentationalonesometimesisn'
tenough.Whatisneededisguidance.
Mygoalistoprovideaguideforyou.
Awordofwarning
TherearesomereallyexcellentJavaScriptpeopleoutthere.I'
mnotoneofthem.
I'
mreallyjusttheguyItalkedaboutinthepreviousparagraph.Iknowathingortwoaboutdevelopingbackendwebapplications,butI'
mstillnewto"
JavaScriptandstillnewtoNode.js.IlearnedsomeofthemoreadvancedaspectsofJavaScriptjustrecently.I'
mnotexperienced.
Whichiswhythisisno"
fromnovicetoexpert"
book.It'
smorelike"
fromnovicetoadvancednovice"
.
IfIdon'
tfail,thenthiswillbethekindofdocumentIwishIhadwhenstartingwithNode.js.
Server-sideJavaScript
ThefirstincarnationsofJavaScriptlivedinbrowsers.Butthisisjustthecontext.Itdefineswhatyoucandowiththelanguage,butitdoesn'
tsaymuchaboutwhatthelanguageitselfcando.JavaScriptisa"
complete"
language:
youcanuseitinmanycontextsandachieveeverythingwithityoucanachievewithanyother"
language.
Node.jsreallyisjustanothercontext:
itallowsyoutorunJavaScriptcodeinthebackend,outsideabrowser.
InordertoexecutetheJavaScriptyouintendtoruninthebackend,itneedstobeinterpretedand,well,executed.ThisiswhatNode.jsdoes,bymakinguseofGoogle'
sV8VM,thesameruntimeenvironmentforJavaScriptthatGoogleChromeuses.
Plus,Node.jsshipswithalotofusefulmodules,soyoudon'
thavetowriteeverythingfromscratch,likeforexamplesomethingthatoutputsastringontheconsole.
Thus,Node.jsisreallytwothings:
aruntimeenvironmentandalibrary.
Inordertomakeuseofthese,youneedtoinstallNode.js.Insteadofrepeatingtheprocesshere,Ikindlyaskyoutovisit
theofficialinstallationinstructions.Pleasecomebackonceyouareupandrunning.
"
Ok,let'
sjustjumpinthecoldwaterandwriteourfirstNode.jsapplication:
"
Openyourfavoriteeditorandcreateafilecalled
helloworld.js.Wewantittowrite"
toSTDOUT,andhereisthecodeneededtodothat:
console.log("
);
Savethefile,andexecuteitthroughNode.js:
nodehelloworld.js
Thisshouldoutput
HelloWorld
onyourterminal.
Ok,thisstuffisboring,right?
Let'
swritesomerealstuff.
AfullblownwebapplicationwithNode.js
Theusecases
Let'
skeepitsimple,butrealistic:
∙Theusershouldbeabletouseourapplicationwithawebbrowser
∙Theusershouldseeawelcomepagewhenrequestinghttp:
//domain/startwhichdisplaysafileuploadform
∙Bychoosinganimagefiletouploadandsubmittingtheform,thisimageshouldthenbeuploadedtohttp:
//domain/upload,whereitisdisplayedoncetheuploadisfinished
Fairenough.Now,youcouldachievethisgoalbygooglingandhackingtogethersomething.Butthat'
snotwhatwewanttodohere.
Furthermore,wedon'
twanttowriteonlythemostbasiccodetoachievethegoal,howeverelegantandcorrectthiscodemightbe.WewillintentionallyaddmoreabstractionthannecessaryinordertogetafeelingforbuildingmorecomplexNode.jsapplications.
Theapplicationstack
sdissectourapplication.Whichpartsneedtobeimplementedinordertofulfilltheusecases?
∙Wewanttoservewebpages,thereforeweneedan
HTTPserver
∙Ourserverwillneedtoanswerdifferentlytorequests,dependingonwhichURLtherequestwasaskingfor,thusweneedsomekindof
router
inordertomaprequeststorequesthandlers
∙Tofulfilltherequeststhatarrivedattheserverandhavebeenroutedusingtherouter,weneedactual
requesthandlers
∙TherouterprobablyshouldalsotreatanyincomingPOSTdataandgiveittotherequesthandlersinaconvenientform,thusweneed
requestdatahandling
∙WenotonlywanttohandlerequestsforURLs,wealsowanttodisplaycontentwhentheseURLsarerequested,whichmeansweneedsomekindof
viewlogic
therequesthandlerscanuseinordertosendcontenttotheuser'
sbrowser
∙Lastbutnotleast,theuserwillbeabletouploadimages,sowearegoingtoneedsomekindof
uploadhandling
whichtakescareofthedetails
sthinkamomentabouthowwewouldbuildthi