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

华纳云新人下单立减40元/香港云服务器月付60元起,香港双向CN2(GIA)

华纳云(HNCloud Limited)是一家专业的全球数据中心基础服务提供商,总部在香港,隶属于香港联合通讯国际有限公司,拥有香港政府颁发的商业登记证明,保证用户的安全性和合规性。 华纳云是APNIC 和 ARIN 会员单位。主要提供数据中心基础服务、互联网业务解决方案, 以及香港服务器租用、香港服务器托管、香港云服务器、美国云服务器,云计算、云安全技术研发等产品和服务。其中云服务器基于成熟的 ...

青果云(590元/年),美国vps洛杉矶CN2 GIA主机测评 1核1G 10M

青果网络QG.NET定位为高效多云管理服务商,已拥有工信部颁发的全网云计算/CDN/IDC/ISP/IP-VPN等多项资质,是CNNIC/APNIC联盟的成员之一,2019年荣获国家高薪技术企业、福建省省级高新技术企业双项荣誉。那么青果网络作为国内主流的IDC厂商之一,那么其旗下美国洛杉矶CN2 GIA线路云服务器到底怎么样?官方网站:https://www.qg.net/CPU内存系统盘流量宽带...

华纳云CN2高防1810M带宽独享,三网直cn218元/月,2M带宽;独服/高防6折购

华纳云怎么样?华纳云是香港老牌的IDC服务商,成立于2015年,主要提供中国香港/美国节点的服务器及网络安全产品、比如,香港服务器、香港云服务器、香港高防服务器、香港高防IP、美国云服务器、机柜出租以及云虚拟主机等。以极速 BGP 冗余网络、CN2 GIA 回国专线以及多年技能经验,帮助全球数十万家企业实现业务转型攀升。华纳云针对618返场活动,华纳云推出一系列热销产品活动,香港云服务器低至3折,...

internalservererror为你推荐
"参与方式一:线上招聘(简历投递)"设置routeuctools为什么一直服务器暂不可用wordpress模板我在wordpress模板下载了一套模板,做了www.xuanqianbao.com这个站,模板的原站是www.rrzdm.com.一样的模板,我在文件在插入图片,却不能在首页显示,他的网站却可以.直linux防火墙设置LINUX系统怎么关闭防火墙苹果appstore宕机为什App Store下载软件 到了一半就停了 不动了pletecuteftp本公司www文档下载怎么下载百度文档加多宝与王老吉加多宝王老吉有什么区别吗?
最便宜的vps 提供香港vps 看国外视频直播vps 三级域名网站 enom vps.net wavecom 工信部icp备案号 cdn联盟 网站卫士 台湾谷歌 linux使用教程 中国电信网络测速 阿里云免费邮箱 免费稳定空间 存储服务器 hdchina 删除域名 建站行业 dbank 更多