Node.js Modules: Import and use Functions from Another File
文章推薦指數: 80 %
To include functions defined in another file in Node.js, we need to import the module. we will use the require keyword at the top of the file. SkiplinksSkiptoprimarynavigationSkiptocontentSkiptofooterStanleyUliliarticlesAboutContactMeTogglesearchTogglemenuintroductionCreatingandExportingaModuleCreatingaModuleExportingamoduleImportingamoduleinNode.jsExportingMultipleFunctionsandValuesImportamodulefromadirectoryTypesofmodulesinNode.jsLocalModulesCoreModulesThird-PartyModulesConclusionintroductionInNode.js,anyfilethatconsistsofJavaScriptcodeinafileendingwith.jsisamodule.Amodulecancontaindefinitionsoffunctions,classes,objects,orvariablesthatcanbereferencedorusedinanotherJavascriptfile.Whenyourapplicationstartsgettinglarger,maintainingasinglefilebecomesadifficulttask.itiseasytogetlostinthecodebaseandlosetrackofwhataparticularpieceofcodeisdoing.Theproblemget’sworsewhenyouaredebuggingcode.Tomakeiteasiertomaintain,reuseandorganizecode,youneedtosplitthecodeintomultiplefiles.Thisprocessiscalledmodularization.Eachmodulecontainsfunctionsorclassesthathandleaspecificfunctionality.Functionsinonemodulecanbeimportedandcalledinothermodulessavingyoufromhavingtocopyfunctiondefinitionsintotheotherfiles.Amodulecanbeeditedordebuggedseparatelymakingiteasierforyoutoaddorremovenewfeatures.Inthistutorial,youwilllearnhowtocreateNode.jsmodules.Youwillalsolearnhowtoincludefunctionsdefinedinonefileandusetheminanotherfile.Someofthetopicswewillexploreare:CreatingandExportingamoduleImportingaModuleExportingmultiplefunctionsandvaluesfromamoduleImportingamodulefromadirectoryTypesofmodulesTofollowthistutorial,createanodejsdirectoryinyourhomedirectoryoranywhereyouwant.mkdirnodejs Getintothenodejsdirectory.cdnodejs Nowyouareallsettofollowthetutorialandpracticethecode.CreatingandExportingaModuleCreatingaModuleModulesarecreatedinNode.jsbycreatingaJavaScriptfile.Everytimeyoucreateanewfilewith.jsextension,itbecomesamodule.Let’swriteourfirstmodule.Wewillstartbycreatingtwofunctionstodosimplecalculations.Typethefollowingcodeandsaveitaslib.jsinsideyournodejsdirectory.lib.jsfunctionadd(x,y){ returnx+y; } functionsubtract(x,y){ returnx-y; } Thefilelib.jsisnowamodule.Thetwofunctionsadd()andsubtractareonlyavailableinourfile.Theyencapsulated,meaningtheycannotbeaccessedoutsidethefile.ifyoutrytocalltheminanotherfile,youwillgetanerror.Insidethenode.jsfolder.Createanotherfilemain.js.Let’strytocallthefunctionadd()inourfile.main.jsconstresult=add(4,4); console.log(result); Runthefilewithnode.js.nodemain.js Youwillgetanerror.ReferenceError:addisnotdefined ExportingamoduleAswehavelearnedinthepreviousexample,wecan’taccessthefunctionsdefinedinonemoduleinanothermodulebydefault.Toaccessthemodulefunctions,wehavetoexportthefunctionsandimporttheminthefilewewanttocallthefunctions.Letsexporttheadd()functioninthelib.jsfile.Gototheendofthefilelib.jsandaddmodule.exports={add}.lib.jsfunctionadd(x,y){ returnx+y; } functionsubtract(x,y){ returnx-y; } //addthecodebelow module.exports={add}; What’shappeningnowinourlib.jsfileisthatwehaveaddedtheadd()functiontomodule.exportsobject.Addingthefunctiontomodule.exportswillmakeitavailableinanyfilethatimportsthelib.jsmodule.Youarenotlimitedtoexportingfunctions.Youcanexportvariables,objects,andclasses,etc.ImportingamoduleinNode.jsToincludefunctionsdefinedinanotherfileinNode.js,weneedtoimportthemodule.wewillusetherequirekeywordatthetopofthefile.Theresultofrequireisthenstoredinavariablewhichisusedtoinvokethefunctionsusingthedotnotation.Toseethatinaction,let’simportthelib.jsmodulebyrequiringitinsidethemain.jsfileandinvoketheadd()functionwithdotnotation.main.jsconstlib=require("./lib"); constresult=lib.add(4,4); console.log(`Theresultis:${result}`); Ifwerunourcodenow,weshouldgetthefollowingoutput:Theresultis:8 What’shappeninginthecodeaboveisthatweareimportingthelib.jsmodule.constlib=require("./lib"); Whenimportingthefilelib.js,itisimportanttoprefixitwith./insiderequire.ThistellsNode.jsthatweareimportingalocalmodule(amodulecreatedbyyourselfsuchasthelib.jsmodule).Whenrequiringthemodule,youcanleaveoutthefileasextensionaswehavedonerequire('./lib')oryoucanputthefileextension(.js)ofthefileyouwanttoimport.constlib=require("./lib.js");//puttinganextensionalsoworks Whenrequireimportsthemodule,itreturnsanobjectwithadd()asit’samethodandstoresitinthelibvariable.constlib=require("./lib"); console.log(lib); Output:{add:[Function:add]} Theobjectreturnedbyrequireisthemodule.exportsobjectfromthemodulelib.jswereweexportedonlyonemethodadd().Sinceanobjectiswhatisreturnedbyrequire,toaccesstheadd()function,weuseddotnotationbyprefixingtheobjectname(lib)tocalltheadd(4,4)functionandthenstoretheresultofthefunctionintheresultvariable.constresult=lib.add(4,4); ExportingMultipleFunctionsandValuesThereareacoupleofwaystoexportmultiplefunctionsandvalueswithmodule.exports.lib.jsfunctionadd(x,y){ returnx+y; } functionsubtract(x,y){ returnx-y; } constnum=33; module.exports={add,subtract,num}; Inmain.jsfile,youcanimportthemasfollows:constlib=require("./lib"); console.log(lib.add(4,4));//8 console.log(lib.subtract(8,4));//4 console.log(lib.num); Youcanalsousethedestructuringsyntaxtounpackthepropertiesoftheobjectreturnedbyrequireandstoretheminvariables.const{add,subtract,num}=require("./lib"); console.log(add(4,4));//8 console.log(subtract(8,4));//4 console.log(num);//33 Anotherwaytoexportmultiplefunctionsistodefinethefunctionsinsidemodule.exportsobject.lib.jsmodule.exports={ add:function(x,y){ returnx+y; }, subtract:function(x,y){ returnx-y; }, num:33, }; Youcanalsodefineeachfunctionindepedentlyasamethodofmodule.exports.lib.jsmodule.exports.add=function(x,y){ returnx+y; }; module.exports.subtract=function(x,y){ returnx-y; }; module.exports.num=33; ImportamodulefromadirectoryInsidetheprojectdirectory,createadirectorymathsandmovethelib.jsfileintoit.├──main.js └──maths └──lib.js Toimportlib.jsfileinsidethedirectory,requirelib.jsbyprefixingitwiththedirectoryname.Inmain.jsfile.constlib=require("./maths/lib"); console.log(lib.add(4,4));//8 console.log(lib.subtract(8,4));//4 console.log(lib.num);//33 TypesofmodulesinNode.jsLocalModulesCoreModulesThird-PartyModules.LocalModulesThesearemodulesthatyoucancreateyourselfandusetheminyourapplication.Agoodexampleofalocalmoduleisthemodulelib.jswecreatedandimportedinthemain.jsfileinthistutorial.importingLocalmodulesTorecap,toimportalocalmodule,youhavetorequire('./filename')orrequire('./filename.js')orrequire('./path/filename.js').constmoduleName=require('./filename.js'); Youdon’thavetoaddthe“.js”extension,Node.jscanstillloadyourlocalmodulewithoutitaswehavelearned.constmoduleName=require('./filename'); CoreModulesThesearemodulesthatcomewithNode.jsbydefault.Youdonothavetodownloadtheminyourproject.Someofthemostpopularandfrequentlyusedcoremodulesarefs,os,path,etc.ImportingcoremodulesToimportacoremodule,youhavetousetherequire()methodwiththecoremodule’snamepassedastheargument.constfileSystem=require("fs"); Third-PartyModulesThird-partymodulesaremodulesthataredownloadedwithapackagemanagersuchasnpm.Thesemodulesareusuallystoredinthenode_modulesfolder.Youcaninstallthird-partymodulesgloballyorlocallyinyourproject.Examplesofthirdpartymodulesareexpress,mongoose,react,etc.ImportingThird-PartyModulesToimportathird-partymodule,youhavetousetherequire()methodthattakesthethird-partymodule’snameasanargument.constfileSystem=require("express"); ConclusionInthistutorial,wecoveredhowtocreateandexportamodule,importamoduleandwentoverdifferentwaystoexportmultiplefunctionsandvalues,andalsodifferenttypesofmodulesinNode.js.Ifyouhaveanyinsightsorsuggestions,feelfreetoleaveacomment.TwitterFacebookRedditSignUpforMyNewsletterPreviousNextYouMayAlsoEnjoy2021YearinReviewandinto20225minutereadThepurposeistotrackmygoals,accomplishmentsandfailuressothatinthefutureIcanseehowfarIhavecome.2020YearinReview6minutereadIhavebeenreadingyearinreviewpostslately,theyhaveinspiredmetostartahabitofdocumentingmyannualprogress.AsynchronousProgrammingwithCallbacksinJavaScript14minutereadInthisarticle,youaregoingtolearnaboutsynchronousandasynchronousprogramminginJavaScript.Afterthat,youwilllearnthesignificanceofcallback...UnderstandingMethodChaininginJavaScript4minutereadintroductionMethodchainingisatechniquethatinvolvescallingmultiplemethodsonthesameobjectinachain-likesequence.Thisismadepossiblebyretu...Enteryoursearchterm...
延伸文章資訊
- 1CommonJS modules | Node.js v18.9.1 Documentation
Package authors should include the "type" field, even in packages where all sources are CommonJS....
- 2Node.js Modules - W3Schools
What is a Module in Node.js? Consider modules to be the same as JavaScript libraries. A set of fu...
- 3String.prototype.includes() - JavaScript - MDN Web Docs
The includes() method performs a case-sensitive search to determine whether one string may be fou...
- 4Array.prototype.includes() - JavaScript - MDN Web Docs
The includes() method determines whether an array includes a certain value among its entries, ret...
- 5C++ addons | Node.js v18.9.1 Documentation
js includes other statically linked libraries including OpenSSL. These other libraries are locate...