How to include Functions from other files in Node.js
文章推薦指數: 80 %
Require() function: It is an inbuilt function and is the easiest way to include functions that exist in separate files. The basic functionality ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#HTMLJavaScriptPHPSQLScalaPerlGoLanguageKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage HTMLCSSJavaScriptjQueryPHPBootstrapNodeJSReactJSAngularJSExpressJSTailwindBulmaFoundationReactDesktopjQueryUIjQueryMobileTypeScriptp5.jsTensorflow.jsPrimerCSS RelatedArticles ▲RelatedArticlesInstallationofNode.jsonLinuxHowtoupdateNode.jsandNPMtonextversion?Node.jsfs.readFileSync()MethodHowtoupdateNPM?Node.jsfs.readFile()MethodDifferencebetweenFetchandAxios.jsformakinghttprequestsNode.jsfs.writeFile()MethodHowtoinstallthepreviousversionofnode.jsandnpm?Node.jsforEach()functionExpress.jsres.render()FunctionMongoose|findByIdAndUpdate()FunctionExpress.jsres.sendFile()FunctionDifferencebetweennode.jsrequireandES6importandexportNode.jsfs.readdirSync()MethodLoginformusingNode.jsandMongoDBNode.jsfs.readdir()MethodWhatarethedifferencesbetweennpmandnpx?HowtouseanES6importinNode.js?Express.jsres.redirect()FunctionDifferencebetweenpromiseandasyncawaitinNode.jsNode.jspath.resolve()MethodExpress.jsres.json()FunctionHowtoreadandwriteExcelfileinNode.js?DifferencebetweennpmandyarnExpress.jsres.send()FunctionHowtoreadandwriteJSONfileusingNode.js?Howtoresolve'node'isnotrecognizedasaninternalorexternalcommanderrorafterinstallingNode.js?HowtouseClassinNode.js?Mongoosefind()FunctionHowtoconnectNode.jswithReact.js?InstallationofNode.jsonLinuxHowtoupdateNode.jsandNPMtonextversion?Node.jsfs.readFileSync()MethodHowtoupdateNPM?Node.jsfs.readFile()MethodDifferencebetweenFetchandAxios.jsformakinghttprequestsNode.jsfs.writeFile()MethodHowtoinstallthepreviousversionofnode.jsandnpm?Node.jsforEach()functionExpress.jsres.render()FunctionMongoose|findByIdAndUpdate()FunctionExpress.jsres.sendFile()FunctionDifferencebetweennode.jsrequireandES6importandexportNode.jsfs.readdirSync()MethodLoginformusingNode.jsandMongoDBNode.jsfs.readdir()MethodWhatarethedifferencesbetweennpmandnpx?HowtouseanES6importinNode.js?Express.jsres.redirect()FunctionDifferencebetweenpromiseandasyncawaitinNode.jsNode.jspath.resolve()MethodExpress.jsres.json()FunctionHowtoreadandwriteExcelfileinNode.js?DifferencebetweennpmandyarnExpress.jsres.send()FunctionHowtoreadandwriteJSONfileusingNode.js?Howtoresolve'node'isnotrecognizedasaninternalorexternalcommanderrorafterinstallingNode.js?HowtouseClassinNode.js?Mongoosefind()FunctionHowtoconnectNode.jswithReact.js?HowtoincludeFunctionsfromotherfilesinNode.js?ViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 29Jun,2020ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle Codereusabilityisanimportantpillarinmoderndayprogramming.CodeReusemeansthepracticeofusinganexistingcodeforanewfunctionorsoftware.Inthisarticle,wewouldlearnhowtousefunctionsfromotherfilesinNode.js. ThisfunctionalitycanbeeasilyimplementedusingtheinbuiltexportandrequirefunctionsofNode.js.Export:Themodule.exportsinNode.jsisusedtoexportanyliteral,functionorobjectasamodule.ItisusedtoincludeJavaScriptfileintoNode.jsapplications.Themoduleissimilartovariablethatisusedtorepresentthecurrentmoduleandexportsisanobjectthatisexposedasamodule.Require()function:Itisaninbuiltfunctionandistheeasiestwaytoincludefunctionsthatexistinseparatefiles.ThebasicfunctionalityofrequireisthatitreadsaJavaScriptfile,executesthefile,andthenproceedstoreturntheexportobject.Letusconsiderthefollowingbasicexample:Filename:cal.jsfunctionsum(x,y){ return(x+y);} functionsub(x,y){ return(x-y);} functionmul(x,y){ return(x*y);} module.exports={add,sub,mul,div};Intheaboveexample,weusethemodule.exportsfunctionsothatwecanuseitinotherfiles.Thefunctionsareenclosedwithincurlybrackets({})accordingtotheformattoexportmultiplefunctionsatatime.Supposewewantedtousethesefunctionsinmain.js,thenitcanbeeasilydoneusingthefollowingcode:Filename:main.js//requiringcal.jsfileconstcal=require("./cal.js") //Usingthefunctionsfromcal.js constsum=cal.sum(2,2);console.log(sum); constsub=cal.sub(10,5);console.log(sub); constproduct=cal.mul(2,3);console.log(product);Thiswillimportthecal.jsfileanditsfunctionsintothemain.jsfile.Runmain.jsfileusingthefollowingcommand:nodemain.jsOutput: 4 5 6 MyPersonalNotes arrow_drop_upSave LikePreviousHowtohidethetableheaderusingJavaScript?Next HowtodefinestyleinformationofadocumentusingHTML5?RecommendedArticlesPage:18,Jun1931,Jul1926,Apr2007,Aug2006,Dec1804,Feb2114,Apr2019,Feb2128,Mar2227,May2231,May2231,Jan2205,Mar2128,Mar1903,May1930,Aug1927,Feb2027,Feb2002,Mar2026,Apr2026,Apr2021,May2031,May2029,Jun20ArticleContributedBy:hiteshkowdiki@hiteshkowdikiVotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertArticleTags:Node.js-MiscNode.jsWebTechnologiesWebtechnologiesQuestionsReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register
延伸文章資訊
- 1Node.js Modules: Import and use Functions from Another File
To include functions defined in another file in Node.js, we need to import the module. we will us...
- 2include-nodejs - npm
Refactoring everything without breaking some is hard. @include is a lightweight, small, and conve...
- 3CommonJS modules | Node.js v18.9.1 Documentation
Package authors should include the "type" field, even in packages where all sources are CommonJS....
- 4How to include Functions from other files in Node.js
Require() function: It is an inbuilt function and is the easiest way to include functions that ex...
- 5In Node.js, how do I "include" functions from my other files?
Let's say I have a file called app.js. Pretty simple: var express = ...