Aliasedinternal

internalservererror  时间:2021-03-06  阅读:()
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

美国高防云服务器 1核 1G 26元/月 香港/日本站群服务器 E5 16G 1600元/月 触摸云

触摸云国内IDC/ISP资质齐全商家,与香港公司联合运营, 已超8年运营 。本次为大家带来的是双12特惠活动,美国高防|美国大宽带买就可申请配置升档一级[CPU内存宽带流量选一]升档方式:CPU内存宽带流量任选其一,工单申请免费升级一档珠海触摸云科技有限公司官方网站:https://cmzi.com/可新购免费升档配置套餐:地区CPU内存带宽数据盘价格购买地址美国高防 1核 1G10M20G 26...

HaloCloud:日本软银vps100M/200M/500M带宽,,¥45.00元/月

halocloud怎么样?halocloud是一个于2019下半年建立的商家,主要提供日本软银VPS,广州移动VDS,株洲联通VDS,广州移动独立服务器,Halo邮局服务,Azure香港1000M带宽月抛机器等。日本软银vps,100M/200M/500M带宽,可看奈飞,香港azure1000M带宽,可以解锁奈飞等流媒体,有需要看奈飞的朋友可以入手!点击进入:halocloud官方网站地址日本vp...

10gbiz($2.36/月),香港/洛杉矶CN2 GIA线路VPS,香港/日本独立服务器

10gbiz发布了9月优惠方案,针对VPS、独立服务器、站群服务器、高防服务器等均提供了一系列优惠方面,其中香港/洛杉矶CN2 GIA线路VPS主机4折优惠继续,优惠后最低每月仅2.36美元起;日本/香港独立服务器提供特价款首月1.5折27.43美元起;站群/G口服务器首月半价,高防服务器永久8.5折等。这是一家成立于2020年的主机商,提供包括独立服务器租用和VPS主机等产品,数据中心包括美国洛...

internalservererror为你推荐
2019支付宝五福支付宝集五福在哪里看到美要求解锁iPhone怎么用爱思手机助手解锁苹果手机?阅读http抢米网抢小米手机需要下什么软件 速求2828商机网千元能办厂?28商机网是真的吗?billboardchina美国Billboard公告牌年度10大金曲最新华丽合辑400电话查询能查出400电话是什么地区的吗灌水机什么是论坛灌水机?在哪里可以下载到呢?zencart模板zen cart套用模板后,外观控制显示红色打不开,为什么?ie假死我的电脑,IE一直会死机,怎么回事???
域名服务器 济南域名注册 cn域名备案 GGC z.com 国内永久免费云服务器 seovip parseerror cdn加速是什么 香港亚马逊 东莞idc 中国电信测速网站 阿里云邮箱怎么注册 亿库 sonya restart godaddy中文 美国服务器 9929 电脑主机配置 更多