MasteringNodeNodeisanexcitingnewplatformdevelopedbyRyanDahl,allowingJavaScriptdeveloperstocreateextremelyhighperformanceserversbyleveragingGoogle'sV8JavaScriptengine,andasynchronousI/O.
InMasteringNodewewilldiscoverhowtowritehighconcurrencywebservers,utilizingtheCommonJSmodulesystem,node'scorelibraries,thirdpartymodules,highlevelwebdevelopmentandmore.
MasteringNode1InstallingNodeInthischapterwewillbelookingattheinstallationandcompilationofnode.
Althoughthereareseveralwayswemayinstallnode,wewillbelookingathomebrew,nDistro,andthemostflexiblemethod,ofcourse-compilingfromsource.
HomebrewHomebrewisapackagemanagementsystemforOSXwritteninRuby,isextremelywelladopted,andeasytouse.
Toinstallnodeviathebrewexecutablesimplyrun:$brewinstallnode.
jsnDistronDistroisadistributiontoolkitfornode,whichallowscreationandinstallationofnodedistroswithinseconds.
AnnDistroissimplyadotfilenamed.
ndistrowhichdefinesmoduleandnodebinaryversiondependencies.
Intheexamplebelowwespecifythenodebinaryversion0.
1.
102,aswellasseveral3rdpartymodules.
node0.
1.
102modulesenchalabsconnectmodulevisionmediaexpress1.
0.
0beta2modulevisionmediaconnect-formmodulevisionmediaconnect-redismodulevisionmediajademodulevisionmediaejsAnymachinethatcanrunashellscriptcaninstalldistributions,andkeepsdependenciesdefinedtoasingledirectorystructure,makingiteasytomaintainandeploy.
nDistrousespre-compilednodebinariesmakingthemextremelyfasttoinstall,andmoduletarballswhicharefetchedfromGitHubviawgetorcurl(autodetected).
TogetstartedwefirstneedtoinstallnDistroitself,belowwecdtoourbindirectoryofchoice,curltheshellscript,andpipetheresponsetoshwhichwillinstallnDistrotothecurrentdirectory:$cd/usr/local/bin&&curlhttp://github.
com/visionmedia/ndistro/raw/master/install|shNextwecanplacethecontentsofourexamplein.
/.
ndistro,andexecutendistrowithnoarguments,promptingtheprogramtoloadtheconfig,andstartinstalling:$ndistroInstallationoftheexampletooklessthan17secondsonmymachine,andoutputsthefollowingstdoutindicatingsuccess.
Notbadforanentirestack!
.
.
.
installingnode-0.
1.
102-i386.
.
.
installingconnect.
.
.
installingexpress1.
0.
0beta2.
.
.
installingbin/express.
.
.
installingconnect-form.
.
.
installingconnect-redis.
.
.
installingjade.
.
.
installingbin/jade.
.
.
installingejs.
.
.
installationcompleteInstallingNode2BuildingFromSourceTobuildandinstallnodefromsource,wefirstneedtoobtainthecode.
Thefirstmethodofdoingsoisviagit,ifyouhavegitinstalledyoucanexecute:$gitclonehttp://github.
com/ry/node.
git&&cdnodeForthosewithoutgit,orwhoprefernottouseit,wecanalsodownloadthesourceviacurl,wget,orsimilar:$curl-#http://nodejs.
org/dist/node-v0.
1.
99.
tar.
gz>node.
tar.
gz$tar-zxfnode.
tar.
gzNowthatwehavethesourceonourmachine,wecanrun.
/configurewhichdiscoverswhichlibrariesareavailablefornodetoutilizesuchasOpenSSLfortransportsecuritysupport,CandC++compilers,etc.
makewhichbuildsnode,andfinallymakeinstallwhichwillinstallnode.
$.
/configure&&make&&makeinstallInstallingNode3GlobalsAswehavelearnt,node'smodulesystemdiscouragestheuseofglobals;howevernodeprovidesafewimportantglobalsforusetoutilize.
Thefirstandmostimportantistheprocessglobal,whichexposesprocessmanipulationsuchassignalling,exiting,theprocessid(pid),andmore.
Otherglobals,suchastheconsoleobject,areprovidedtothoseusedtowritingJavaScriptforwebbrowsers.
consoleTheconsoleobjectcontainsseveralmethodswhichareusedtooutputinformationtostdoutorstderr.
Let'stakealookatwhateachmethoddoes:console.
log()Themostfrequentlyusedconsolemethodisconsole.
log(),whichsimplywritestostdoutandappendsalinefeed(\n).
Currentlyaliasedasconsole.
info().
console.
log('wahoo');//=>wahooconsole.
log({foo:'bar'});//=>[objectObject]console.
error()Identicaltoconsole.
log(),howeverwritestostderr.
Aliasedasconsole.
warn()aswell.
console.
error('databaseconnectionfailed');console.
dir()Utilizesthesysmodule'sinspect()methodtopretty-printtheobjecttostdout.
console.
dir({foo:'bar'});//=>{foo:'bar'}console.
assert()Assertsthatthegivenexpressionistruthy,orthrowsanexception.
console.
assert(connected,'Databaseconnectionfailed');processTheprocessobjectisplasteredwithgoodies.
Firstwewilltakealookatsomepropertiesthatprovideinformationaboutthenodeprocessitself:process.
versionThenodeversionstring,forexample"v0.
1.
103".
Globals4process.
installPrefixTheinstallationprefix.
Inmycase"/usr/local",asnode'sbinarywasinstalledto"/usr/local/bin/node".
process.
execPathThepathtotheexecutableitself"/usr/local/bin/node".
process.
platformTheplatformyouarerunningon.
Forexample,"darwin".
process.
pidTheprocessid.
process.
cwd()Returnsthecurrentworkingdirectory.
Forexample:cd~&&nodenode>process.
cwd()"/Users/tj"process.
chdir()Changesthecurrentworkingdirectorytothepathpassed.
process.
chdir('/foo');process.
getuid()Returnsthenumericaluseridoftherunningprocess.
process.
setuid()Setstheeffectiveuseridfortherunningprocess.
Thismethodacceptsbothanumericalid,aswellasastring.
Forexamplebothprocess.
setuid(501),andprocess.
setuid('tj')arevalid.
process.
getgid()Returnsthenumericalgroupidoftherunningprocess.
process.
setgid()Similartoprocess.
setuid()howeveroperatesonthegroup,alsoacceptinganumericalvalueorstringrepresentation.
Forexample,process.
setgid(20)orprocess.
setgid('www').
process.
envAnobjectcontainingtheuser'senvironmentvariables.
Forexample:{PATH:'/Users/tj/.
gem/ruby/1.
8/bin:/Users/tj/.
nvm/current/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11Globals5,PWD:'/Users/tj/ebooks/masteringnode',EDITOR:'mate',LANG:'en_CA.
UTF-8',SHLVL:'1',HOME:'/Users/tj',LOGNAME:'tj',DISPLAY:'/tmp/launch-YCkT03/org.
x:0',_:'/usr/local/bin/node',OLDPWD:'/Users/tj'}process.
argvWhenexecutingafilewiththenodeexecutableprocess.
argvprovidesaccesstotheargumentvector,thefirstvaluebeingthenodeexecutable,secondbeingthefilename,andremainingvaluesbeingtheargumentspassed.
Forexample,oursourcefile.
/src/process/misc.
jscanbeexecutedbyrunning:$nodesrc/process/misc.
jsfoobarbazinwhichwecallconsole.
dir(process.
argv),outputtingthefollowing:['node','/Users/tj/EBooks/masteringnode/src/process/misc.
js','foo','bar','baz']process.
exit()Theprocess.
exit()methodissynonymouswiththeCfunctionexit(),inwhichanexitcode>0ispassedtoindicatefailure,or0ispassedtoindicatesuccess.
Wheninvoked,theexiteventisemitted,allowingashorttimeforarbitraryprocessingtooccurbeforeprocess.
reallyExit()iscalledwiththegivenstatuscode.
process.
on()TheprocessitselfisanEventEmitter,allowingyoutodothingslikelistenforuncaughtexceptionsviatheuncaughtExceptionevent:process.
on('uncaughtException',function(err){console.
log('gotanerror:%s',err.
message);process.
exit(1);});setTimeout(function(){thrownewError('fail');},100);process.
kill()process.
kill()methodsendsthesignalpassedtothegivenpid,defaultingtoSIGINT.
Intheexamplebelow,wesendtheSIGTERMsignaltothesamenodeprocesstoillustratesignaltrapping,afterwhichweoutput"terminating"andexit.
Notethatthesecondtimeoutof1000millisecondsisneverreached.
process.
on('SIGTERM',function(){Globals6console.
log('terminating');process.
exit(1);});setTimeout(function(){console.
log('sendingSIGTERMtoprocess%d',process.
pid);process.
kill(process.
pid,'SIGTERM');},500);setTimeout(function(){console.
log('nevercalled');},1000);errnoTheprocessobjectishostoftheerrornumbers,whichreferencewhatyouwouldfindinC-land.
Forexample,process.
EPERMrepresentsapermissionbasederror,whileprocess.
ENOENTrepresentsamissingfileordirectory.
TypicallytheseareusedwithinbindingstobridgethegapbetweenC++andJavaScript,butthey'reusefulforhandlingexceptionsaswell:if(err.
errno===process.
ENOENT){//Displaya404"NotFound"page}else{//Displaya500"InternalServerError"page}Globals7EventsTheconceptofan"event"iscrucialtonode,andisusedheavilythroughoutcoreand3rd-partymodules.
Node'scoremoduleeventssuppliesuswithasingleconstructor,EventEmitter.
EmittingEventsTypicallyanobjectinheritsfromEventEmitter,howeveroursmallexamplebelowillustratestheAPI.
Firstwecreateanemitter,afterwhichwecandefineanynumberofcallbacksusingtheemitter.
on()method,whichacceptsthenameoftheeventandarbitraryobjectspassedasdata.
Whenemitter.
emit()iscalled,weareonlyrequiredtopasstheeventname,followedbyanynumberofarguments(inthiscasethefirstandlastnamestrings).
varEventEmitter=require('events').
EventEmitter;varemitter=newEventEmitter;emitter.
on('name',function(first,last){console.
log(firstlast);});emitter.
emit('name','tj','holowaychuk');emitter.
emit('name','simon','holowaychuk');InheritingFromEventEmitterAmorepracticalandcommonuseofEventEmitteristoinheritfromit.
ThismeanswecanleaveEventEmitter'sprototypeuntouchedwhileutilizingitsAPIforourownmeansofworlddomination!
Todoso,webeginbydefiningtheDogconstructor,whichofcoursewillbarkfromtimetotime(alsoknownasanevent).
varEventEmitter=require('events').
EventEmitter;functionDog(name){this.
name=name;}HereweinheritfromEventEmittersowecanusethemethodsitprovides,suchasEventEmitter#on()andEventEmitter#emit().
Ifthe__proto__propertyisthrowingyouoff,don'tworry,we'llbecomingbacktothislater.
Dog.
prototype.
__proto__=EventEmitter.
prototype;NowthatwehaveourDogsetup,wecancreate.
.
.
Simon!
WhenSimonbarks,wecanletstdoutknowbycallingconsole.
log()withinthecallback.
Thecallbackitselfiscalledinthecontextoftheobject(akathis).
varsimon=newDog('simon');simon.
on('bark',function(){console.
log(this.
name+'barked');});Barktwicepersecond:Events8setInterval(function(){simon.
emit('bark');},500);RemovingEventListenersAswehaveseen,eventlistenersaresimplyfunctionswhicharecalledwhenweemit()anevent.
WecanremovetheselistenersbycallingtheremoveListener(type,callback)method,althoughthisisn'tseenoften.
Intheexamplebelowweemitthemessage"foobar"every300milliseconds,whichhasacallbackofconsole.
log().
After1000milliseconds,wecallremoveListener()withthesameargumentsthatwepassedtoon()originally.
WecouldalsohaveusedremoveAllListeners(type),whichremovesalllistenersregisteredtothegiventype.
varEventEmitter=require('events').
EventEmitter;varemitter=newEventEmitter;emitter.
on('message',console.
log);setInterval(function(){emitter.
emit('message','foobar');},300);setTimeout(function(){emitter.
removeListener('message',console.
log);},1000);Events9BuffersTohandlebinarydata,nodeprovidesuswiththeglobalBufferobject.
BufferinstancesrepresentmemoryallocatedindependentlyofV8'sheap.
ThereareseveralwaystoconstructaBufferinstance,andmanywaysyoucanmanipulateitsdata.
ThesimplestwaytoconstructaBufferfromastringistosimplypassastringasthefirstargument.
Asyoucanseeinthelogoutput,wenowhaveabufferobjectcontaining5bytesofdatarepresentedinhexadecimal.
varhello=newBuffer('Hello');console.
log(hello);//=>console.
log(hello.
toString());//=>"Hello"Bydefault,theencodingis"utf8",butthiscanbeoverriddenbypassingastringasthesecondargument.
Forexample,theellipsisbelowwillbeprintedtostdoutasthe"&"characterwhenin"ascii"encoding.
varbuf=newBuffer('—');console.
log(buf.
toString());varbuf=newBuffer(ascii');console.
log(buf.
toString());//=>&Analternative(butinthiscasefunctionalityequivalent)methodistopassanarrayofintegersrepresentingtheoctetstream.
varhello=newBuffer([0x48,0x65,0x6c,0x6c,0x6f]);Bufferscanalsobecreatedwithanintegerrepresentingthenumberofbytesallocated,afterwhichwecancallthewrite()method,providinganoptionaloffsetandencoding.
Below,weprovideanoffsetof2bytestooursecondcalltowrite()(buffering"Hel")andthenwriteanothertwobyteswithanoffsetof3(completing"Hello").
varbuf=newBuffer(5);buf.
write('He');buf.
write('l',2);buf.
write('lo',3);console.
log(buf.
toString());//=>"Hello"The.
lengthpropertyofabufferinstancecontainsthebytelengthofthestream,asopposedtonativestrings,whichsimplyreturnthenumberofcharacters.
Forexample,theellipsischaracter'—'consistsofthreebytes,sothebufferwillrespondwiththebytelength(3),andnotthecharacterlength(1).
varellipsis=newBuffer(utf8');console.
log('—stringlength:%d'length);stringlength:1console.
log('—bytelength:%d',ellipsis.
length);bytelength:3console.
log(ellipsis);Buffers10//=>Todeterminethebytelengthofanativestring,passittotheBuffer.
byteLength()method.
TheAPIiswritteninsuchawaythatitisString-like.
Forexample,wecanworkwith"slices"ofaBufferbypassingoffsetstotheslice()method:varchunk=buf.
slice(4,9);console.
log(chunk.
toString());//=>"some"Alternatively,whenexpectingastring,wecanpassoffsetstoBuffer#toString():varbuf=newBuffer('justsomedata');console.
log(buf.
toString('ascii',4,9));//=>"some"Buffers11StreamsStreamsareanimportantconceptinnode.
ThestreamAPIisaunifiedwaytohandlestream-likedata.
Forexample,datacanbestreamedtoafile,streamedtoasockettorespondtoanHTTPrequest,orstreamedfromaread-onlysourcesuchasstdin.
Fornow,we'llconcentrateontheAPI,leavingstreamspecificstolaterchapters.
ReadableStreamsReadablestreamssuchasanHTTPrequestinheritfromEventEmitterinordertoexposeincomingdatathroughevents.
Thefirstoftheseeventsisthedataevent,whichisanarbitrarychunkofdatapassedtotheeventhandlerasaBufferinstance.
req.
on('data',function(buf){//DosomethingwiththeBuffer});Asweknow,wecancalltoString()onabuffertoreturnastringrepresentationofthebinarydata.
Likewise,wecancallsetEncoding()onastream,afterwhichthedataeventwillemitstrings.
req.
setEncoding('utf8');req.
on('data',function(str){//DosomethingwiththeString});Anotherimportanteventisend,whichrepresentstheendingofdataevents.
Forexample,here'sanHTTPechoserver,whichsimply"pumps"therequestbodydatathroughtotheresponse.
SoifwePOST"helloworld",ourresponsewillbe"helloworld".
varhttp=require('http');http.
createServer(function(req,res){res.
writeHead(200);req.
on('data',function(data){res.
write(data);});req.
on('end',function(){res.
end();});}).
listen(3000);Thesysmoduleactuallyhasafunctiondesignedspecificallyforthis"pumping"action,aptlynamedsys.
pump().
Itacceptsareadstreamasthefirstargument,andwritestreamasthesecond.
varhttp=require('http'),sys=require('sys');http.
createServer(function(req,res){res.
writeHead(200);sys.
pump(req,res);}).
listen(3000);Streams12FileSystemToworkwiththefilesystem,nodeprovidesthe"fs"module.
ThecommandsemulatethePOSIXoperations,andmostmethodsworksynchronouslyorasynchronously.
Wewilllookathowtouseboth,thenestablishwhichisthebetteroption.
WorkingwiththefilesystemLetsstartwithabasicexampleofworkingwiththefilesystem.
Thisexamplecreatesadirectory,createsafileinsideit,thenwritesthecontentsofthefiletoconsole:varfs=require('fs');fs.
mkdir('.
/helloDir',0777,function(err){if(err)throwerr;fs.
writeFile('.
/helloDir/message.
txt','HelloNode',function(err){if(err)throwerr;console.
log('filecreatedwithcontents:');fs.
readFile('.
/helloDir/message.
txt','UTF-8',function(err,data){if(err)throwerr;console.
log(data);});});});Asevidentintheexampleabove,eachcallbackisplacedinthepreviouscallback—thesearereferredtoaschainablecallbacks.
Thispatternshouldbefollowedwhenusingasynchronousmethods,asthere'snoguaranteethattheoperationswillbecompletedintheorderthey'recreated.
Thiscouldleadtounpredictablebehavior.
Theexamplecanberewrittentouseasynchronousapproach:fs.
mkdirSync('.
/helloDirSync',0777);fs.
writeFileSync('.
/helloDirSync/message.
txt','HelloNode');vardata=fs.
readFileSync('.
/helloDirSync/message.
txt','UTF-8');console.
log('filecreatedwithcontents:');console.
log(data);Itisbettertousetheasynchronousapproachonserverswithahighload,asthesynchronousmethodswillcausethewholeprocesstohaltandwaitfortheoperationtocomplete.
Thiswillblockanyincomingconnectionsorotherevents.
FileinformationThefs.
Statsobjectcontainsinformationaboutaparticularfileordirectory.
Thiscanbeusedtodeterminewhattypeofobjectwe'reworkingwith.
Inthisexample,we'regettingallthefileobjectsinadirectoryanddisplayingwhetherthey'reafileoradirectoryobject.
varfs=require('fs');fs.
readdir('/etc/',function(err,files){if(err)throwerr;files.
forEach(function(file){FileSystem13fs.
stat('/etc/'+file,function(err,stats){if(err)throwerr;if(stats.
isFile()){console.
log("%sisfile",file);}elseif(stats.
isDirectory()){console.
log("%sisadirectory",file);}console.
log('stats:%s',JSON.
stringify(stats));});});});WatchingfilesThefs.
watchfilemethodmonitorsafileandfiresaneventwheneverthefileischanged.
varfs=require('fs');fs.
watchFile('.
/testFile.
txt',function(curr,prev){console.
log('thecurrentmtimeis:'+curr.
mtime);console.
log('thepreviousmtimewas:'+prev.
mtime);});fs.
writeFile('.
/testFile.
txt',"changed",function(err){if(err)throwerr;console.
log("filewritecomplete");});Afilecanalsobeunwatchedusingthefs.
unwatchFilemethodcall.
Thisshouldbeusedonceafilenolongerneedstobemonitored.
NodejsDocsforfurtherreadingThenodeAPIdocsareverydetailedandlistallthepossiblefilesystemcommandsavailablewhenworkingwithNodejs.
FileSystem14TCP.
.
.
TCPServers.
.
.
TCPClients.
.
.
TCP15HTTP.
.
.
HTTPServers.
.
.
HTTPClients.
.
.
HTTP16ConnectConnectisa.
.
.
Connect17ExpressExpressisa.
.
.
Express18Testing.
.
.
Expresso.
.
.
Vows.
.
.
Testing19Deployment.
.
.
Deployment20
咖啡主机怎么样?咖啡主机是一家国人主机销售商,成立于2016年8月,之前云服务器网已经多次分享过他家的云服务器产品了,商家主要销售香港、洛杉矶等地的VPS产品,Cera机房 三网直连去程 回程CUVIP优化 本产品并非原生地区本土IP,线路方面都有CN2直连国内,机器比较稳定。咖啡主机目前推出美国洛杉矶弹性轻量云主机仅13元/月起,高防云20G防御仅18元/月;香港弹性云服务器,香港HKBN CN...
Mineserver(ASN142586|UK CompanyNumber 1351696),已经成立一年半。主营香港日本机房的VPS、物理服务器业务。Telegram群组: @mineserver1 | Discord群组: https://discord.gg/MTB8ww9GEA7折循环优惠:JP30(JPCN2宣布产品可以使用)8折循环优惠:CMI20(仅1024M以上套餐可以使用)9折循...
麻花云怎么样?麻花云公司成立于2007年,当前主打产品为安徽移动BGP线路,数据中心连入移动骨干网。提供5M,10M大带宽云主机,香港云服务器产品,数据中心为香港将军澳机房,香港宽频机房 cn2-GIA优质线路、采用HYPER-V,KVM虚拟技术架构一、麻花云官网点击直达麻花云官方网站合肥网联网络科技有限公司优惠码: 专属优惠码:F1B07B 享受85折优惠。最新活动 :双11 云上嗨购 香港云主...
internalservererror为你推荐
支持ipadphpweb破解怎样破解握手包重庆网络公司一九互联网络公司做一个网站大概需要多少钱360和搜狗360游览器和搜狗的哪个好cisco2960配置Cisco2960是二层交换机,怎么可以进入配置界面进行配置。不是说二层交换机不需要配置吗?filezillaserverfilezilla server interface怎么填outlookexpress系统自带的outlook express有什么用?怎么用?重庆400年老树穿楼生长重庆吊脚楼重庆网站制作重庆网站制作,哪家专业,价格最优?文档下载怎么下载百度文档
阿里云搜索 赵容 cloudstack ev证书 panel1 合租空间 免费个人空间 ntfs格式分区 双十一秒杀 闪讯官网 东莞idc 视频服务器是什么 smtp服务器地址 测速电信 石家庄服务器 512内存 godaddy中文 magento主机 卡巴斯基免费版下载 tko 更多