About | Node.js

文章推薦指數: 80 %
投票人數:10人

As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications. In the following "hello world" example, ... About Governance AboutNode.js®Asanasynchronousevent-drivenJavaScriptruntime,Node.jsisdesignedtobuild scalablenetworkapplications.Inthefollowing"helloworld"example,many connectionscanbehandledconcurrently.Uponeachconnection,thecallbackis fired,butifthereisnoworktobedone,Node.jswillsleep. consthttp=require('http'); consthostname='127.0.0.1'; constport=3000; constserver=http.createServer((req,res)=>{ res.statusCode=200; res.setHeader('Content-Type','text/plain'); res.end('HelloWorld'); }); server.listen(port,hostname,()=>{ console.log(`Serverrunningathttp://${hostname}:${port}/`); }); Thisisincontrasttotoday'smorecommonconcurrencymodel,inwhichOSthreads areemployed.Thread-basednetworkingisrelativelyinefficientandvery difficulttouse.Furthermore,usersofNode.jsarefreefromworriesof dead-lockingtheprocess,sincetherearenolocks.Almostnofunctionin Node.jsdirectlyperformsI/O,sotheprocessneverblocksexceptwhentheI/Oisperformedusing synchronousmethodsofNode.jsstandardlibrary.Becausenothingblocks,scalablesystemsarevery reasonabletodevelopinNode.js. Ifsomeofthislanguageisunfamiliar,thereisafullarticleon Blockingvs.Non-Blocking. Node.jsissimilarindesignto,andinfluencedby,systemslikeRuby's EventMachineandPython'sTwisted.Node.jstakestheeventmodelabit further.Itpresentsaneventloopasaruntimeconstructinsteadofasalibrary.Inothersystems, thereisalwaysablockingcalltostarttheevent-loop. Typically,behaviorisdefinedthroughcallbacksatthebeginningofascript,and attheendaserverisstartedthroughablockingcalllikeEventMachine::run(). InNode.js,thereisnosuchstart-the-event-loopcall.Node.jssimplyenterstheeventloopafterexecutingtheinputscript.Node.js exitstheeventloopwhentherearenomorecallbackstoperform.Thisbehavior islikebrowserJavaScript—theeventloopishiddenfromtheuser. HTTPisafirst-classcitizeninNode.js,designedwithstreamingandlow latencyinmind.ThismakesNode.jswellsuitedforthefoundationofaweb libraryorframework. Node.jsbeingdesignedwithoutthreadsdoesn'tmeanyoucan'ttake advantageofmultiplecoresinyourenvironment.Childprocessescanbespawned byusingourchild_process.fork()API,andaredesignedtobeeasyto communicatewith.Builtuponthatsameinterfaceistheclustermodule, whichallowsyoutosharesocketsbetweenprocessestoenableloadbalancing overyourcores. ↑Scrolltotop



請為這篇文章評分?