How To Write and Run Your First Program in Node.js

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

How To Write and Run Your First Program in Node.js · Step 1 — Outputting to the Console · Step 2 — Running the Program · Step 3 — Receiving User ... Getalertedwhenassetsaredown,slow,orvulnerabletoSSLattacks—allfreeforamonth.LearnmoreProductsPricingDocsSigninTutorialsQuestionsLearningPathsTechTalksGetInvolvedProductDocsSearchCommunity/SignUpCONTENTSIntroductionPrerequisitesStep1—OutputtingtotheConsoleStep2—RunningtheProgramStep3—ReceivingUserInputviaCommandLineArgumentsStep4—AccessingEnvironmentVariablesStep5—AccessingaSpecifiedEnvironmentVariableStep6—RetrievingAnArgumentinResponsetoUserInputStep7—ViewingMultipleEnvironmentVariablesStep8—HandlingUndefinedInputConclusionRelatedHowToInstallanUpstreamVersionofNode.jsonUbuntu12.04ViewHowToInstallAndRunANode.jsAppOnCentos6.464bitViewTutorialSeries:HowToCodeinNode.js1/14HowToWriteandRunYourFirstPrograminNode.js2/14HowToUsetheNode.jsREPL3/14HowToUseNode.jsModuleswithnpmandpackage.json4/14HowToCreateaNode.jsModule5/14HowToWriteAsynchronousCodeinNode.js6/14HowToTestaNode.jsModulewithMochaandAssert7/14HowToCreateaWebServerinNode.jswiththeHTTPModule8/14UsingBuffersinNode.js9/14UsingEventEmittersinNode.js10/14HowToDebugNode.jswiththeBuilt-InDebuggerandChromeDevTools11/14HowToLaunchChildProcessesinNode.js12/14HowToWorkwithFilesusingthefsModuleinNode.js13/14HowToCreateanHTTPClientwithCoreHTTPinNode.js14/14HowToCodeinNode.jseBook//Tutorial//HowToWriteandRunYourFirstPrograminNode.jsPublishedonAugust14,2019·UpdatedonMarch18,2022JavaScriptNode.jsDevelopmentByStackAbuseDeveloperandauthoratDigitalOcean.TheauthorselectedtheOpenInternet/FreeSpeechFundtoreceiveadonationaspartoftheWriteforDOnationsprogram. Introduction Node.jsisapopularopen-sourceruntimeenvironmentthatcanexecuteJavaScriptoutsideofthebrowserusingtheV8JavaScriptengine,whichisthesameengineusedtopowertheGoogleChromewebbrowser’sJavaScriptexecution.TheNoderuntimeiscommonlyusedtocreatecommandlinetoolsandwebservers. LearningNode.jswillallowyoutowriteyourfront-endcodeandyourback-endcodeinthesamelanguage.UsingJavaScriptthroughoutyourentirestackcanhelpreducetimeforcontextswitching,andlibrariesaremoreeasilysharedbetweenyourback-endserverandfront-endprojects. Also,thankstoitssupportforasynchronousexecution,Node.jsexcelsatI/O-intensivetasks,whichiswhatmakesitsosuitablefortheweb.Real-timeapplications,likevideostreaming,orapplicationsthatcontinuouslysendandreceivedata,canrunmoreefficientlywhenwritteninNode.js. Inthistutorialyou’llcreateyourfirstprogramwiththeNode.jsruntime.You’llbeintroducedtoafewNode-specificconceptsandbuildyourwayuptocreateaprogramthathelpsusersinspectenvironmentvariablesontheirsystem.Todothis,you’lllearnhowtooutputstringstotheconsole,receiveinputfromtheuser,andaccessenvironmentvariables. Prerequisites Tocompletethistutorial,youwillneed: Node.jsinstalledonyourdevelopmentmachine.ThistutorialusesNode.jsversion10.16.0.ToinstallthisonmacOSorUbuntu18.04,followthestepsinHowtoInstallNode.jsandCreateaLocalDevelopmentEnvironmentonmacOSorthe“InstallingUsingaPPA”sectionofHowToInstallNode.jsonUbuntu18.04. AbasicknowledgeofJavaScript,whichyoucanfindhere:HowToCodeinJavaScript. Step1—OutputtingtotheConsole Towritea“Hello,World!”program,openupacommandlinetexteditorsuchasnanoandcreateanewfile: nanohello.js Withthetexteditoropened,enterthefollowingcode: hello.js console.log("HelloWorld"); TheconsoleobjectinNode.jsprovidessimplemethodstowritetostdout,stderr,ortoanyotherNode.jsstream,whichinmostcasesisthecommandline.Thelogmethodprintstothestdoutstream,soyoucanseeitinyourconsole. InthecontextofNode.js,streamsareobjectsthatcaneitherreceivedata,likethestdoutstream,orobjectsthatcanoutputdata,likeanetworksocketorafile.Inthecaseofthestdoutandstderrstreams,anydatasenttothemwillthenbeshownintheconsole.Oneofthegreatthingsaboutstreamsisthatthey’reeasilyredirected,inwhichcaseyoucanredirecttheoutputofyourprogramtoafile,forexample. SaveandexitnanobypressingCTRL+X,whenpromptedtosavethefile,pressY.Nowyourprogramisreadytorun. Step2—RunningtheProgram Torunthisprogram,usethenodecommandasfollows: nodehello.js Thehello.jsprogramwillexecuteanddisplaythefollowingoutput: OutputHelloWorld TheNode.jsinterpreterreadthefileandexecutedconsole.log("HelloWorld");bycallingthelogmethodoftheglobalconsoleobject.Thestring"HelloWorld"waspassedasanargumenttothelogfunction. Althoughquotationmarksarenecessaryinthecodetoindicatethatthetextisastring,theyarenotprintedtothescreen. Havingconfirmedthattheprogramworks,let’smakeitmoreinteractive. Step3—ReceivingUserInputviaCommandLineArguments EverytimeyouruntheNode.js“Hello,World!”program,itproducesthesameoutput.Inordertomaketheprogrammoredynamic,let’sgetinputfromtheuseranddisplayitonthescreen. Commandlinetoolsoftenacceptvariousargumentsthatmodifytheirbehavior.Forexample,runningnodewiththe--versionargumentprintstheinstalledversioninsteadofrunningtheinterpreter.Inthisstep,youwillmakeyourcodeacceptuserinputviacommandlinearguments. Createanewfilearguments.jswithnano: nanoarguments.js Enterthefollowingcode: arguments.js console.log(process.argv); TheprocessobjectisaglobalNode.jsobjectthatcontainsfunctionsanddataallrelatedtothecurrentlyrunningNode.jsprocess.Theargvpropertyisanarrayofstringscontainingallthecommandlineargumentsgiventoaprogram. SaveandexitnanobytypingCTRL+X,whenpromptedtosavethefile,pressY. Nowwhenyourunthisprogram,youprovideacommandlineargumentlikethis: nodearguments.jshelloworld Theoutputlookslikethefollowing: Output['/usr/bin/node', '/home/sammy/first-program/arguments.js', 'hello', 'world'] Thefirstargumentintheprocess.argvarrayisalwaysthelocationoftheNode.jsbinarythatisrunningtheprogram.Thesecondargumentisalwaysthelocationofthefilebeingrun.Theremainingargumentsarewhattheuserentered,inthiscase:helloandworld. Wearemostlyinterestedintheargumentsthattheuserentered,notthedefaultonesthatNode.jsprovides.Openthearguments.jsfileforediting: nanoarguments.js Changeconsole.log(process.arg);tothefollowing: arguments.js console.log(process.argv.slice(2)); Becauseargvisanarray,youcanuseJavaScript’sbuilt-inslicemethodthatreturnsaselectionofelements.Whenyouprovidetheslicefunctionwith2asitsargument,yougetalltheelementsofargvthatcomesafteritssecondelement;thatis,theargumentstheuserentered. Re-runtheprogramwiththenodecommandandthesameargumentsaslasttime: nodearguments.jshelloworld Now,theoutputlookslikethis: Output['hello','world'] Nowthatyoucancollectinputfromtheuser,let’scollectinputfromtheprogram’senvironment. Step4—AccessingEnvironmentVariables Environmentvariablesarekey-valuedatastoredoutsideofaprogramandprovidedbytheOS.Theyaretypicallysetbythesystemoruserandareavailabletoallrunningprocessesforconfigurationorstatepurposes.YoucanuseNode’sprocessobjecttoaccessthem. Usenanotocreateanewfileenvironment.js: nanoenvironment.js Addthefollowingcode: environment.js console.log(process.env); TheenvobjectstoresalltheenvironmentvariablesthatareavailablewhenNode.jsisrunningtheprogram. Saveandexitlikebefore,andruntheenvironment.jsfilewiththenodecommand. nodeenvironment.js Uponrunningtheprogram,youshouldseeoutputsimilartothefollowing: Output{SHELL:'/bin/bash', SESSION_MANAGER: 'local/digitalocean:@/tmp/.ICE-unix/1003,unix/digitalocean:/tmp/.ICE-unix/1003', COLORTERM:'truecolor', SSH_AUTH_SOCK:'/run/user/1000/keyring/ssh', XMODIFIERS:'@im=ibus', DESKTOP_SESSION:'ubuntu', SSH_AGENT_PID:'1150', PWD:'/home/sammy/first-program', LOGNAME:'sammy', GPG_AGENT_INFO:'/run/user/1000/gnupg/S.gpg-agent:0:1', GJS_DEBUG_TOPICS:'JSERROR;JSLOG', WINDOWPATH:'2', HOME:'/home/sammy', USERNAME:'sammy', IM_CONFIG_PHASE:'2', LANG:'en_US.UTF-8', VTE_VERSION:'5601', CLUTTER_IM_MODULE:'xim', GJS_DEBUG_OUTPUT:'stderr', LESSCLOSE:'/usr/bin/lesspipe%s%s', TERM:'xterm-256color', LESSOPEN:'|/usr/bin/lesspipe%s', USER:'sammy', DISPLAY:':0', SHLVL:'1', PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin', DBUS_SESSION_BUS_ADDRESS:'unix:path=/run/user/1000/bus', _:'/usr/bin/node', OLDPWD:'/home/sammy'} Keepinmindthatmanyoftheenvironmentvariablesyouseearedependentontheconfigurationandsettingsofyoursystem,andyouroutputmaylooksubstantiallydifferentthanwhatyouseehere.Ratherthanviewingalonglistofenvironmentvariables,youmightwanttoretrieveaspecificone. Step5—AccessingaSpecifiedEnvironmentVariable Inthisstepyou’llviewenvironmentvariablesandtheirvaluesusingtheglobalprocess.envobjectandprinttheirvaluestotheconsole. Theprocess.envobjectisasimplemappingbetweenenvironmentvariablenamesandtheirvaluesstoredasstrings.LikeallobjectsinJavaScript,youaccessanindividualpropertybyreferencingitsnameinsquarebrackets. Opentheenvironment.jsfileforediting: nanoenvironment.js Changeconsole.log(process.env);to: environment.js console.log(process.env["HOME"]); Savethefileandexit.Nowruntheenvironment.jsprogram: nodeenvironment.js Theoutputnowlookslikethis: Output/home/sammy Insteadofprintingtheentireobject,younowonlyprinttheHOMEpropertyofprocess.env,whichstoresthevalueofthe$HOMEenvironmentvariable. Again,keepinmindthattheoutputfromthiscodewilllikelybedifferentthanwhatyouseeherebecauseitisspecifictoyoursystem.Nowthatyoucanspecifytheenvironmentvariabletoretrieve,youcanenhanceyourprogrambyaskingtheuserforthevariabletheywanttosee. Step6—RetrievingAnArgumentinResponsetoUserInput Next,you’llusetheabilitytoreadcommandlineargumentsandenvironmentvariablestocreateacommandlineutilitythatprintsthevalueofanenvironmentvariabletothescreen. Usenanotocreateanewfileecho.js: nanoecho.js Addthefollowingcode: echo.js constargs=process.argv.slice(2); console.log(process.env[args[0]]); Thefirstlineofecho.jsstoresallthecommandlineargumentsthattheuserprovidedintoaconstantvariablecalledargs.Thesecondlineprintstheenvironmentvariablestoredinthefirstelementofargs;thatis,thefirstcommandlineargumenttheuserprovided. Saveandexitnano,thenruntheprogramasfollows: nodeecho.jsHOME Now,theoutputwouldbe: Output/home/sammy TheargumentHOMEwassavedtotheargsarray,whichwasthenusedtofinditsvalueintheenvironmentviatheprocess.envobject. Atthispointyoucannowaccessthevalueofanyenvironmentvariableonyoursystem.Toverifythis,tryviewingthefollowingvariables:PWD,USER,PATH. Retrievingsinglevariablesisgood,butlettingtheuserspecifyhowmanyvariablestheywantwouldbebetter. Step7—ViewingMultipleEnvironmentVariables Currently,theapplicationcanonlyinspectoneenvironmentvariableatatime.Itwouldbeusefulifwecouldacceptmultiplecommandlineargumentsandgettheircorrespondingvalueintheenvironment.Usenanotoeditecho.js: nanoecho.js Editthefilesothatithasthefollowingcodeinstead: echo.js constargs=process.argv.slice(2); args.forEach(arg=>{ console.log(process.env[arg]); }); TheforEachmethodisastandardJavaScriptmethodonallarrayobjects.Itacceptsacallbackfunctionthatisusedasititeratesovereveryelementofthearray.YouuseforEachontheargsarray,providingitacallbackfunctionthatprintsthecurrentargument’svalueintheenvironment. Saveandexitthefile.Nowre-runtheprogramwithtwoarguments: nodeecho.jsHOMEPWD Youwouldseethefollowingoutput: [secondary_labelOutput] /home/sammy /home/sammy/first-program TheforEachfunctionensuresthateverycommandlineargumentintheargsarrayisprinted. Nowyouhaveawaytoretrievethevariablestheuserasksfor,butwestillneedtohandlethecasewheretheuserentersbaddata. Step8—HandlingUndefinedInput Toseewhathappensifyougivetheprogramanargumentthatisnotavalidenvironmentvariable,runthefollowing: nodeecho.jsHOMEPWDNOT_DEFINED Theoutputwilllooksimilartothefollowing: [secondary_labelOutput] /home/sammy /home/sammy/first-program undefined Thefirsttwolinesprintasexpected,andthelastlineonlyhasundefined.InJavaScript,anundefinedvaluemeansthatavariableorpropertyhasnotbeenassignedavalue.BecauseNOT_DEFINEDisnotavalidenvironmentvariable,itisshownasundefined. Itwouldbemorehelpfultoausertoseeanerrormessageiftheircommandlineargumentwasnotfoundintheenvironment. Openecho.jsforediting: nanoecho.js Editecho.jssothatithasthefollowingcode: echo.js constargs=process.argv.slice(2); args.forEach(arg=>{ letenvVar=process.env[arg]; if(envVar===undefined){ console.error(`Couldnotfind"${arg}"inenvironment`); }else{ console.log(envVar); } }); Here,youhavemodifiedthecallbackfunctionprovidedtoforEachtodothefollowingthings: Getthecommandlineargument’svalueintheenvironmentandstoreitinavariableenvVar. CheckifthevalueofenvVarisundefined. IftheenvVarisundefined,thenweprintahelpfulmessageindicatingthatitcouldnotbefound. Ifanenvironmentvariablewasfound,weprintitsvalue. Note:Theconsole.errorfunctionprintsamessagetothescreenviathestderrstream,whereasconsole.logprintstothescreenviathestdoutstream.Whenyourunthisprogramviathecommandline,youwon’tnoticethedifferencebetweenthestdoutandstderrstreams,butitisgoodpracticetoprinterrorsviathestderrstreamsothattheycanbeeasieridentifiedandprocessedbyotherprograms,whichcantellthedifference. Nowrunthefollowingcommandoncemore: nodeecho.jsHOMEPWDNOT_DEFINED Thistimetheoutputwillbe: [secondary_labelOutput] /home/sammy /home/sammy/first-program Couldnotfind"NOT_DEFINED"inenvironment Nowwhenyouprovideacommandlineargumentthat’snotanenvironmentvariable,yougetaclearerrormessagestatingso. Conclusion Yourfirstprogramdisplayed“HelloWorld”tothescreen,andnowyouhavewrittenaNode.jscommandlineutilitythatreadsuserargumentstodisplayenvironmentvariables. Ifyouwanttotakethisfurther,youcanchangethebehaviorofthisprogramevenmore.Forexample,youmaywanttovalidatethecommandlineargumentsbeforeyouprint.Ifanargumentisundefined,youcanreturnanerror,andtheuserwillonlygetoutputifallargumentsarevalidenvironmentvariables. Ifyou’dliketocontinuelearningNode.js,youcanreturntotheHowToCodeinNode.jsseries,orbrowseprogrammingprojectsandsetupsonourNodetopicpage. Nextinseries:HowToUsetheNode.jsREPL->Wanttolearnmore?JointheDigitalOceanCommunity!JoinourDigitalOceancommunityofoveramilliondevelopersforfree!GethelpandshareknowledgeinourQuestions&Answerssection,findtutorialsandtoolsthatwillhelpyougrowasadeveloperandscaleyourprojectorbusiness,andsubscribetotopicsofinterest.SignupTutorialSeries:HowToCodeinNode.jsNode.jsisapopularopen-sourceruntimeenvironmentthatcanexecuteJavaScriptoutsideofthebrowser.TheNoderuntimeiscommonlyusedforback-endwebdevelopment,leveragingitsasynchronouscapabilitiestocreatenetworkingapplicationsandwebservers.Nodealsoisapopularchoiceforbuildingcommandlinetools. Inthisseries,youwillgothroughexercisestolearnthebasicsofhowtocodeinNode.js,gainingpowerfultoolsforback-endandfullstackdevelopmentintheprocess. SubscribeJavaScriptNode.jsDevelopmentBrowseSeries:14articles1/14HowToWriteandRunYourFirstPrograminNode.js2/14HowToUsetheNode.jsREPL3/14HowToUseNode.jsModuleswithnpmandpackage.jsonExpandtoviewallAbouttheauthorsStackAbuseauthorDeveloperandauthoratDigitalOcean.BrianMacDonaldeditorSeniorAcquisitionsEditorEditoratDigitalOcean,formerbookeditoratPragmatic,O’Reilly,andothers.Occasionalconferencespeaker.Highlynerdy. Stilllookingforananswer?AskaquestionSearchformorehelpWasthishelpful?YesNoComments1CommentsThistextboxdefaultstousingMarkdowntoformatyouranswer.Youcantype!refinthistextareatoquicklysearchourfullsetoftutorials,documentation&marketplaceofferingsandinsertthelink!SignInorSignUptoCommentemmsio•September11,2020greattutorial!!thankyou.understep8,thefourthsectionhasanerror,outputs“Couldnotfind“${arg}”inenvironment”insteadofinsertingtheNOT_DEFINED.heresthecorrection: constargs=process.argv.slice(2); args.forEach(arg=>{ letenvVar=process.env[arg]; if(envVar===undefined){ console.error(Couldnotfind+[arg]+inenvironment); }else{ console.log(envVar); } }); ReplyThisworkislicensedunderaCreativeCommonsAttribution-NonCommercial-ShareAlike4.0InternationalLicense.TryDigitalOceanforfreeClickbelowtosignupandget$200ofcredittotryourproductsover60days!SignupPopularTopicsUbuntuLinuxBasicsJavaScriptReactPythonSecurityApacheMySQLDatabasesDockerKubernetesEbooksBrowsealltopictagsAlltutorialsQuestionsQ&AAskaquestionDigitalOceanProductDocsDigitalOceanSupportEventsTechTalksHacktoberfestDeployGetinvolvedCommunityNewsletterHollie'sHubforGoodWriteforDOnationsCommunitytoolsandintegrationsHatchStartupprogramJointheTechTalkSuccess!Thankyou!Pleasecheckyouremailforfurtherdetails.Pleasecompleteyourinformation!TutorialsQuestionsLearningPathsWriteforUsHacktoberfestToolsHomepagePricingProductOverviewMarketplaceControlPanelDocumentationContactSupportContactSalesSignin



請為這篇文章評分?