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

妮妮云(43元/月 ) 香港 8核8G 43元/月 美国 8核8G

妮妮云的来历妮妮云是 789 陈总 张总 三方共同投资建立的网站 本着“良心 便宜 稳定”的初衷 为小白用户避免被坑妮妮云的市场定位妮妮云主要代理市场稳定速度的云服务器产品,避免新手购买云服务器的时候众多商家不知道如何选择,妮妮云就帮你选择好了产品,无需承担购买风险,不用担心出现被跑路 被诈骗的情况。妮妮云的售后保证妮妮云退款 通过于合作商的友好协商,云服务器提供2天内全额退款,超过2天不退款 物...

SugarHosts新增Windows云服务器sugarhosts六折无限流量云服务器六折优惠

SugarHosts糖果主机商我们较早的站长们肯定是熟悉的,早年是提供虚拟主机起家的,如今一直还在提供虚拟主机,后来也有增加云服务器、独立服务器等。数据中心涵盖美国、德国、香港等。我们要知道大部分的海外主机商都只提供Linux系统云服务器。今天,糖果主机有新增SugarHosts夏季六折的优惠,以及新品Windows云服务器/云VPS上线。SugarHosts Windows系统云服务器有区分限制...

HostYun(月18元),CN2直连香港大带宽VPS 50M带宽起

对于如今的云服务商的竞争着实很激烈,我们可以看到国内国外服务商的各种内卷,使得我们很多个人服务商压力还是比较大的。我们看到这几年的服务商变动还是比较大的,很多新服务商坚持不超过三个月,有的是多个品牌同步进行然后分别的跑路赚一波走人。对于我们用户来说,便宜的服务商固然可以试试,但是如果是不确定的,建议月付或者主力业务尽量的还是注意备份。HostYun 最近几个月还是比较活跃的,在前面也有多次介绍到商...

internalservererror为你推荐
linux防火墙设置LINUX系统怎么关闭防火墙德国iphone禁售令有人说苹果手机从2017年开始,中国禁售了企业电子邮局企业邮箱怎么使用?波音737起飞爆胎飞机会爆胎的吗?重庆网站制作请问一下重庆网站建设哪家公司做得好,价格又便宜哦?360免费建站搭建卡盟分站(卡乐购系统,免费360网站收录)只要29元,想建的找2208647548!资费标准中国移动4g18元套餐介绍徐州商标求江苏徐州地区的商标代理机构!tumblr上不去我家里的网络打不开个别网站厦门三五互联科技股份有限公司厦门三五互联科技股份有限公司怎么样?
国外php主机 uk2 国内永久免费云服务器 腾讯云数据库 香港机房托管 特价空间 permitrootlogin 双12活动 长沙服务器 铁通流量查询 数字域名 ftp教程 柚子舍官网 韩国名字大全 360云服务 登陆空间 重庆电信服务器托管 贵阳电信测速 服务器论坛 美国迈阿密 更多