Upload
alfonsoprofox2922
View
11
Download
0
Embed Size (px)
DESCRIPTION
NodeJs Program 2
Citation preview
NODEPROGRAM2014
PRESENTERAzatMardan:
USFederalgovernmentStartups(Storify)Corporations(DocuSign)9booksonNode
@azat_cowebapplog.com
AGENDADAY11. Introductions2. JavaScriptFundamentals3. Break4. Node.jsFundamentals5. Debuggingandothertools6. NPM:utils,fs,buffer,url,path7. LearnYouNodeWorkshop8. Lunch9. HelloWorldServer10. Heroku11. StreamAdventureWorkshop12. FunctionalJavaScriptWorkshop
AGENDADAY21. NoSQLandMongoDB2. RESTAPI3. Break4. Express.jsFundamentals5. JadeandStylus6. ExpressRESTAPI7. ExpressWorksWorkshop8. Lunch9. Production10. Electivepersonalprojects
JAVASCRIPTFUNDAMENTALS
EXPRESSIVNESS
LOOSETYPINGstringbooleannumberregexpobject
OBJECTLITERALNOTATIONvarobj={a:4,b:9,x:"node.js"}
FUNCTIONS
varf=function(){...}
functionf2(){...}
functionf3(){...return"ok"}
ARRAYSvararr=[1,2,3]arr[0]//==1
PROTOTYPALNATUREPseudo-classical(new,Object,prototype)Functionalinheritancepattern
FUNCTIONALINHERITANCEvarvehicle=function(name){return{name:name,speed:0,accelerate:function(speedIncrease){this.speed+=speedIncreaseconsole.log(this)}}}
varcar1=vehicle('toyota')car1.accelerate(10)console.log(car1.name+'isgoingat'+car1.speed)
CONVENTIONSNamesIndentationSemi-colonsComma-firststyle
NOMODULES
CLOSURES
GLOBALANDPRIVATEVARS
IMMEDIATELY-INVOKEDFUNCTIONEXPRESSIONS
;(function(){...}())
KEYWORD"THIS"
PITFALLSLeakingvarsintoglobalspaceUsingwrong"this"contextUsingwrong==or===MissingbreakinaswitchcaseNotusing"return"whenneededDealingwithpseudo-classicalinheritance
EXERCISEWritea"class"bookwithfunctionalinheritancepattern:
TakesthenameoptionHasamethodreadthattakesnumberofpagesRemembersthenumberofthelastpageread
ANSWERvarbook=function(name){return{name:name,lastPageRead:1,read:function(pages){this.lastPageRead+=pages}}}
varpracticalNode=book('PracticalNode.js')practicalNode.read(101)console.log('lastpagereadfor'+practicalNode.name+'is'+practicalNode.lastPageRead)
NODE.JSFUNDAMENTALS
EVENTLOOPconsole.log('a')setTimeout(function(){console.log('b')},200)console.log('c')
NONBLOCKINGI/OGoogleChromeV8withC++andJS/ECMASuperefficient!CanbeblockedbysynccodeCanbeblockedbylotsofcomputations
READ-EVAL-PRINTLOOP(a.k.a.Console)inNode.js
$node-v$node>
LAUNCHINGNODE.JSSCRIPTS$nodeprogram.js$nodescript.js$node-e"console.log('helloworld')"
NODE.JSPROCESSINFORMATION$node-e"console.log(process)"
process.argvprocess.envprocess.pid
ACCESSINGGLOBALSCOPEINNODE.JSglobal
Never:
IMPORTINGANDEXPORTINGMODULESImport:
varfs=require('fs')varexpress=require('express')
Export:module.exports={...}module.exports=function(){...}exports.a=function(){}
exports=...
BUFFERBufferisaNode.jsbinarydatatype
__DIRNAMEVS.PROCESS.CWDvarpath=__dirname+fileNameconsole.log(process.cwd)
EXERCISE
Writetwofiles:
1. amodule2. aprogramthatexecutesamethodfromthatmodule
Program:
ANSWERModule(module.js):
exports.f=function(arr,num){returnarr.slice(num)}
varmodule=require('./module')vararr=[1,2,3]console.log(module.f(arr,2))//[3]
COREMODULESnoneedtoinstallwithNPM
NET
HTTP
PATH
FS
URL
STRINGDECODER
CRYPTO
DEBUGGINGANDOTHERTOOLSNodeInspectorWebStormnodemon/supervisor/forever/node-devForemanhttp-server/node-static(static)SublimeText2anditsplugins
NPM
[email protected]$npminstallexpress--save$npminstallexpress--save-dev
PACKAGE.JSON{"name":"stream-adventure","version":"2.5.0","description":"aneducationalstreamadventure","bin":{"stream-adventure":"bin/cmd.js"},"dependencies":{"hyperquest":"~0.1.6","ws":"~0.4.25"},"devDependencies":{"tape":"~2.3.0"}}
NODE_MODULES
NPMINSTALL-G
YOULEARNNODE$sudonpminstall-glearnyounode
WORKSHOPTIME
HELLOWORLDSERVER(localsetup)
TUTORIAL&CODE
6.1Node.jsinRapidPrototypingwithJSonpage139inprintand153inPDF.
HELLOWORLDSERVER(Herokudeployment)
NECESSARYCOMPONENTShttps://toolbelt.heroku.comSSHkeysSSHtoHerokuProcfile(web:nodeserver.js)package.json(npminit)
STEPSBRIEFLY1. Makeitworklocally2. AddProcfile,package.json3. $gitinit/add/gitcommit4. $herokucreate5. $gitpush...
TUTORIAL&CODE
6.1.4Deploying"HelloWorld"toPaaSinRapidPrototypingwithJSonpage139in
printand158inPDF.
STREAM
STREAMADVENTURE$sudonpminstall-gstream-adventure$stream-adventure
WORKSHOPTIME
FUNCTIONALJAVASCRIPT$sudonpminstall-gfunctional-javascript-workshop$functional-javascript-workshop
WORKSHOPTIME!
CHAT(run-timememorystore)
TUTORIALS&CODE
6.2Chat:Run-TimeMemoryVersioninRapidPrototypingwithJSonpages146inprint,and159inPDF.
Sourcecode:http://bit.ly/1usviBi
ENDPOINTSPOST/messages.jsonGET/messages.json
FILEStest.js:unittestsmb-server.js:server
MB-SERVER.JSPOST/messages/create.jsonGET/messages/list.json
util.inspectquerystring.parse
exports.getMessagesexports.addMessage
CURL$curlhttp://127.0.0.1:1337$curl-XPOST-d'name=azat&message=hi'http://127.0.0.1:1337
NODESCHOOLhttp://nodeschool.io
DAY2
AGENDADAY2Front-endandback-endoverviewNoSQLandMongoDBRESTAPIBreakExpress.jsFundamentalsJadeandStylusExpressRESTAPIExpressWorksWorkshopLunchProductionElectivepersonalprojects
FRONT-ENDANDBACK-ENDTraditionalwebThickclient/XHRweb
MONGODBBASICSNorelationaldataFast,scalable,andeasilydistributedUsesJavaScriptandBSON(~JSON)!!!
Commands:
Tools:webapplog.com/mongoui
$mongod$mongo
MONGOSHELL>usedbname>showcollections>db.local.find()>db.local.insert({a:1})
Mainmethods:>db.local.find({...})>db.local.insert({...})>db.local.save({...})>db.local.remove({_id:...})>db.local.update({_id:...})
EXERCISE1. StartMongoDBserver2. Createanobjectinacollectionusingshell3. Downloadmongouiandfindyourobject4. Updateyourobject,checkthechanges
NOSQLANDMONGODBPage168inRapidPrototypingwithJS(PDF)
Page154inprint6.4MongoDB
CHATRESTAPI(dbstore)
MONGOHQvaruri=process.env.MONGOHQ_URL||'mongodb://@127.0.0.1:27017'
$herokuaddons:addmongohq:sandbox
MONGODBLIBRARYhttps://github.com/mongodb/node-mongodb-native
Alternatives:MongoskinMongooseMonkMagnolia
TUTORIALS&CODE6.5Chat:MongoDBVersionpage176inPDFand158inprint
http://bit.ly/1AkobeN
EXPRESS.JSFUNDAMENTALS
APPSTRUCTURE
1. Includes2. Instantiations3. Configurations4. Middleware5. Routes6. Boot-up
MIDDLEWAREAlmostalwaysuse:staticbody-parserexpress-sessioncompressionallfromcheatsheet*
*http://bit.ly/Us2qbP
EXPRESS.JSSTACKJadeStylusMongooseorMongoskin
GENERATOR
$npminstall-gexpress-generator
OTHERFRAMEWORKSHapiSailsDerby
manyothersathttp://nodeframeworks.com
EXPRESS.JSHELLOWORLD
CHATRESTAPISERVER(Express.js)
INSPIRATIONCode:https://github.com/azat-co/rest-api-express
Description:http://bit.ly/1jy30tn
JADEANDSTYLUS
EXPRESSWORKSWORKSHOP
PRODUCTION
NODE.JSSTACKHerokuAWSwithNginx+VarnishCache+UpstartscriptsMongoDBorMongoHQ/MongoLab:Mongoskin,MongooseLoggingwithWinston,ElasticKibanaorPapartrailapp
TIPSDeploymentscriptswithSalt(saltstack.com)IncreaseMaxSocketsLockversionsDon'ttrustuserinputHavegooderrorhandlinginplaceUseupstartorforever
ELECTIVEPERSONALPROJECTSFull-stack*IntegrationDeployment
*Comeupwithanidea,e.g.,todoapp
FULL-STACKWriteanfront-endapplicationforChat(ordownloadBackbone.jsversionfromhttps://github.com/azat-co/rpjs/tree/master/board).
MakeitworkwithyourRESTAPIChatserver.
INTEGRATIONWriteanOAuth1.0serverthatcansigninwithTwitter(or
anotherprovider).
YoucanuseOAuth1.0SigninwithEveryauthfromIntroductiontoOAuthwithNode.js
DEPLOYMENT
DeployNode.jsapplication(HelloWorld)toAWS
ENDIfit'snotfun,it'snotJavaScript!
@azat_co