{"id":87673,"date":"2023-05-24T09:00:16","date_gmt":"2023-05-24T03:30:16","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=87673"},"modified":"2023-05-24T09:00:16","modified_gmt":"2023-05-24T03:30:16","slug":"nodejs-modules","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/","title":{"rendered":"Node.js Modules"},"content":{"rendered":"<p>As a student learning Node.js, you may have heard of modules but may not fully understand their importance and how they work. Modules are an essential part of Node.js and are useful to organize code into reusable and maintainable components. In this article, we&#8217;ll explore the basics of Node.js modules and how to use them in your projects.<\/p>\n<h3>What are Modules in Node.js?<\/h3>\n<p>In Node.js, a module is a JavaScript file that contains code, functions, and\/or objects that can be reused in other files. Modules allow developers to create reusable code that can be easily maintained, updated, and shared between projects.<\/p>\n<p>Node.js has a built-in module system that allows you to import and use modules in your code. To create a module, you simply create a new JavaScript file and write the code that you want to reuse. To use the module in another file, you use the require function to import the module.<\/p>\n<h3>How to Use Modules in Node.js<\/h3>\n<p>Using modules in Node.js is straightforward. To use a module, you simply require it in your code using the require function. For example, if you have a module named myModule in a file named myModule.js, you would import it like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const myModule = require('.\/myModule');\n<\/pre>\n<p>In this example, we&#8217;re using the require function to import the myModule module and assigning it to the myModule variable. The \u2018.\/\u2019 before myModule indicates that it is located in the same directory as the file that&#8217;s importing it.<br \/>\nOnce you&#8217;ve imported the module, you can use its functions and objects in your code. For example, if the myModule module has a function named myFunction, you could call it like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">myModule.myFunction();\n<\/pre>\n<h3>Creating and Exporting Nodejs Modules<\/h3>\n<p>To create a module, you simply create a new JavaScript file and write the code that you want to reuse. For example, let&#8217;s say you want to create a module that exports a function that returns the current date and time. You would create a file named dateTime.js and write the following code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">exports.getCurrentDateTime = function() {\n  return new Date();\n};\n<\/pre>\n<p>In this example, we&#8217;re exporting a function named getCurrentDateTime using the exports object. The exports object is a special object in Node.js that allows you to export code from a module.<br \/>\nTo use this module in another file, you would import it like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const dateTime = require('.\/dateTime');\n<\/pre>\n<p>In this example, we&#8217;re using the require function to import the dateTime module and assigning it to the dateTime variable. To use the exported function, we would call it like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const currentDate = dateTime.getCurrentDateTime();\nconsole.log(currentDate);\n<\/pre>\n<p>In this example, we&#8217;re calling the getCurrentDateTime function from the dateTime module and assigning the result to a variable named currentDate. We&#8217;re then logging the value of currentDate to the console.<\/p>\n<p>Apart from this, There are a few additional things that you should know about Node.js modules:<\/p>\n<p><strong>1. Node.js has two types of modules:<\/strong><\/p>\n<ul>\n<li>Core Modules are built-in modules that come with Node.js and can be used without installing any additional packages.<\/li>\n<li>Local Modules are modules that you create yourself or that are installed via NPM.<\/li>\n<\/ul>\n<p>Here are some examples of how to use some of the core modules in Node.js:<\/p>\n<p>a. \u2018fs\u2019 module for file system operations:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"> const fs = require('fs');\n \n \/\/ read a file\n fs.readFile('file.txt', 'utf8', (err, data) =&gt; {\n     if (err) throw err;\n     console.log(data);\n });\n   \n\/\/ write to a file\nfs.writeFile('file.txt', 'Hello world!', (err) =&gt; {\n   if (err) throw err;\n   console.log('The file has been saved!');\n});\n<\/pre>\n<p>b. \u2019http\u2019 module for creating HTTP servers and making HTTP requests:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"> const http = require('http');\n  \n \/\/ create an HTTP server\n http.createServer((req, res) =&gt; {\n   res.writeHead(200, {'Content-Type': 'text\/plain'});\n   res.end('Hello World\\n');\n }).listen(3000);\n  \n console.log('Server running at http:\/\/localhost:3000\/');\n  \n\/\/ make an HTTP request\nhttp.get('http:\/\/www.example.com\/', (res) =&gt; {\n  console.log(`statusCode: ${res.statusCode}`);\n  res.on('data', (data) =&gt; {\n    console.log(data.toString());\n  });\n}).on('error', (error) =&gt; {\n  console.error(error);\n});\n<\/pre>\n<p>c. \u2018path\u2019 module for manipulating file paths:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const path = require('path');\n \n\/\/ join two or more path segments\nconst fullPath = path.join('\/path\/to', 'file.txt');\nconsole.log(fullPath);\n \n\/\/ get the file extension\nconst extension = path.extname(fullPath);\nconsole.log(extension);\n<\/pre>\n<p>Local Modules are modules that you create yourself or that are installed via NPM.<\/p>\n<p>Here an example of how to create and use a local module in Node.js:<\/p>\n<p>a. Create a new file named \u2018myModule.js\u2019 in the same directory as your Node.js application file. This file will contain your custom module code. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"> \/\/ myModule.js\n  \n const myFunction = () =&gt; {\n   console.log('Hello from myFunction!');\n };\n  \n const myObject = {\n   myProperty: 'Hello from myObject!',\n   myMethod: () =&gt; console.log('Hello from myMethod!')\n};\n \nmodule.exports = { myFunction, myObject };\n<\/pre>\n<p>b. In your Node.js application file, use the require() function to import the myModule.js file and its exports. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ app.js\n \nconst myModule = require('.\/myModule');\n \nmyModule.myFunction();  \/\/ output: \"Hello from myFunction!\"\nconsole.log(myModule.myObject.myProperty);  \/\/ output: \"Hello from myObject!\"\nmyModule.myObject.myMethod();  \/\/ output: \"Hello from myMethod!\"\n<\/pre>\n<p>In this example, we define a custom module \u2018myModule\u2019 in a separate file and export two functions and an object. In our Node.js application file, we use the \u2018require()\u2019 function to import \u2018myModule\u2019 and its exports, then use the functions and object in our application.<\/p>\n<p>Third-party modules are pre-built packages of code that you can use in your Node.js application to add functionality without having to write it all from scratch.<\/p>\n<p>Here an example of how to install and use a third-party module in Node.js:<\/p>\n<p>a. Install the \u2018axios\u2019 package using \u2018npm\u2019:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">npm install axios  \n<\/pre>\n<p>b. In your Node.js application file, use the \u2018require()\u2019 function to import the \u2018axios\u2019 module. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ app.js\n  \nconst axios = require('axios');\n \naxios.get('https:\/\/jsonplaceholder.typicode.com\/posts')\n  .then((response) =&gt; {\n   console.log(response.data);\n })\n  .catch((error) =&gt; {\n   console.error(error);\n });\n<\/pre>\n<p>In this example, we install the \u2018axios\u2019 package using \u2018npm\u2019 and then import it into our Node.js application file using the \u2018require()\u2019 function. We then use the \u2018axios\u2019 module to make an HTTP GET request to an external API and log the response data to the console.<\/p>\n<p>When you require a module in Node.js, Node.js will cache the module so that subsequent calls to require the same module will return the cached version. This can help improve the performance of your application by reducing the number of file system reads required to load modules.<\/p>\n<p>You can export multiple functions or objects from a module by attaching them to the exports object. For example, you could export two functions from a module like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">exports.function1 = function() {\n  \/\/ Code for function1\n};\nexports.function2 = function() {\n  \/\/ Code for function2\n};\n<\/pre>\n<p>You can also export a single function or object from a module by assigning it to module.exports. For example, you could export a single function from a module like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">module.exports = function() {\n  \/\/ Code for function\n};\n<\/pre>\n<p>By understanding these additional concepts, you&#8217;ll be better equipped to use Node.js modules effectively in your projects.<\/p>\n<h3>How To Use Own Modules in Nodejs<\/h3>\n<p>To include your own module in Node.js, you need to follow these steps:<\/p>\n<p>1. Create a new file with the name of your module and the \u2018.js\u2019 extension. For example, if your module is called &#8220;myModule&#8221;, create a file named &#8220;myModule.js&#8221;.<\/p>\n<p>2. Define your module inside the file using the \u2018module.exports\u2019 object. For example, if you want to export a function named \u2018myFunction\u2019, you would do it like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">function myFunction() {\n  \/\/ function logic here\n}\nmodule.exports = myFunction;\n<\/pre>\n<p>3. Save the file.<\/p>\n<p>4. In your main Node.js file, require the module using the require() function and assign it to a variable. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const myModule = require('.\/myModule');\n<\/pre>\n<p><strong>Note:<\/strong> that if the module is in the same directory as your main file, you can use the relative path to reference it. If it&#8217;s in a different directory, you&#8217;ll need to specify the full path.<\/p>\n<p>5. You can now use the exported function or any other exported code from your module using the variable you assigned it to. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">myModule();\n<\/pre>\n<p>This will call the \u2018myFunction\u2019 function from your module.<\/p>\n<h3>Conclusion<\/h3>\n<p>Node.js modules are a powerful tool that allow you to organize and reuse code in your projects. By creating and exporting modules, you can easily share code between files and projects, making it easier to maintain and update your code over time. By understanding the basics of Node.js modules and how to use them in your projects, you&#8217;ll be well on your way to becoming a skilled Node.js developer.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>As a student learning Node.js, you may have heard of modules but may not fully understand their importance and how they work. Modules are an essential part of Node.js and are useful to organize&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":87675,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4984],"tags":[5008],"class_list":["post-87673","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-node-js-tutorials","tag-nodejs-modules"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Node.js Modules - TechVidvan<\/title>\n<meta name=\"description\" content=\"Node.js modules are a powerful tool that allow you to organize and reuse code in your projects. See how to use modules in nodejs.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Node.js Modules - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Node.js modules are a powerful tool that allow you to organize and reuse code in your projects. See how to use modules in nodejs.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-05-24T03:30:16+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/04\/node-js-modules.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Node.js Modules - TechVidvan","description":"Node.js modules are a powerful tool that allow you to organize and reuse code in your projects. See how to use modules in nodejs.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/","og_locale":"en_US","og_type":"article","og_title":"Node.js Modules - TechVidvan","og_description":"Node.js modules are a powerful tool that allow you to organize and reuse code in your projects. See how to use modules in nodejs.","og_url":"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-05-24T03:30:16+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/04\/node-js-modules.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Node.js Modules","datePublished":"2023-05-24T03:30:16+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/"},"wordCount":1171,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/04\/node-js-modules.webp","keywords":["nodejs modules"],"articleSection":["Node Js Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/","url":"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/","name":"Node.js Modules - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/04\/node-js-modules.webp","datePublished":"2023-05-24T03:30:16+00:00","description":"Node.js modules are a powerful tool that allow you to organize and reuse code in your projects. See how to use modules in nodejs.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/04\/node-js-modules.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/04\/node-js-modules.webp","width":1200,"height":628,"caption":"node js modules"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-modules\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Node.js Modules"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/87673","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=87673"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/87673\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/87675"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=87673"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=87673"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=87673"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}