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
virmach这是第二波出这种一次性周期的VPS了,只需要缴费1一次即可,用完即抛,也不允许你在后面续费。本次促销的是美国西海岸的圣何塞和美国东海岸的水牛城,周期为6个月,过后VPS会被自动且是强制性取消。需要临时玩玩的,又不想多花钱的用户,可以考虑下!官方网站:https://www.virmach.comTemporary Length Service Specials圣何塞VPS-一次性6个...
俄罗斯vps速度怎么样?俄罗斯vps云主机节点是欧洲十大节点之一,地处俄罗斯首都莫斯科,网络带宽辐射周边欧洲大陆,10G专线连通德国法兰克福、法国巴黎、意大利米兰等,向外连接全球。俄罗斯vps云主机速度快吗、延迟多少?由于俄罗斯数据中心出口带宽充足,俄罗斯vps云主机到全球各地的延迟、速度相对来说都不错。今天,云服务器网(yuntue.com)小编介绍一下俄罗斯vps速度及俄罗斯vps主机推荐!俄...
bgp.to在对日本东京的独立服务器进行6.5折终身优惠促销,低至$120/月;对新加坡独立服务器进行7.5折终身优惠促销,低至$93/月。所有服务器都是直连国内,速度上面相比欧洲、美国有明显的优势,特别适合建站、远程办公等多种用途。官方网站:https://www.bgp.to/dedicated.html主打日本(东京、大阪)、新加坡、香港(CN)、洛杉矶(US)的服务器业务!日本服务器CPU...
internalservererror为你推荐
apple.com.cn苹果官网序列号查询空间文章qq空间日志文章,要求经典新iphone也将禁售苹果手机现在在中国是不是不能卖了googleprGOOGLE PR是什么意思outlookexpressoutlook Express是什么啊?怎么用啊?internetexplorer无法打开为什么Internet Explorer浏览器无法打开filezilla_server如何用FileZilla Server新增FTP帐号邮件eset大飞资讯单仁资讯集团怎么样缤纷网五彩缤纷的黑是什么梗?
如何申请免费域名 便宜服务器 linode kdata 香港cdn 美国php主机 回程路由 轻博 免费ddos防火墙 彩虹ip 百兆独享 国外代理服务器地址 免费申请个人网站 33456 爱奇艺会员免费试用 Updog 海外空间 ebay注册 贵阳电信测速 金主 更多