{"id":72655,"date":"2020-01-14T16:33:36","date_gmt":"2020-01-14T11:03:36","guid":{"rendered":"https:\/\/www.vskills.in\/certification\/tutorial\/?p=72655"},"modified":"2024-04-12T14:22:58","modified_gmt":"2024-04-12T08:52:58","slug":"module-basics-2","status":"publish","type":"page","link":"https:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/","title":{"rendered":"Module Basics"},"content":{"rendered":"<p>In the Node.js module system, each file is treated as a separate module. For example, consider a file named foo.js:<\/p>\n<p>const circle = require(&#8216;.\/circle.js&#8217;);<\/p>\n<p>console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);<\/p>\n<p>On the first line, foo.js loads the module circle.js that is in the same directory as foo.js.<\/p>\n<p>Here are the contents of circle.js:<\/p>\n<p>const { PI } = Math;<\/p>\n<p>exports.area = (r) =&gt; PI * r ** 2;<\/p>\n<p>exports.circumference = (r) =&gt; 2 * PI * r;<\/p>\n<p>The module circle.js has exported the functions area() and circumference(). Functions and objects are added to the root of a module by specifying additional properties on the special exports object.<\/p>\n<p>Variables local to the module will be private, because the module is wrapped in a function by Node.js (see module wrapper). In this example, the variable PI is private to circle.js. The module.exports property can be assigned a new value (such as a function or object). Below, bar.js makes use of the square module, which exports a Square class:<\/p>\n<p>const Square = require(&#8216;.\/square.js&#8217;);<\/p>\n<p>const mySquare = new Square(2);<\/p>\n<p>console.log(`The area of mySquare is ${mySquare.area()}`);<\/p>\n<p>The square module is defined in square.js:<\/p>\n<p>\/\/ Assigning to exports will not modify module, must use module.exports<\/p>\n<p>module.exports = class Square {<\/p>\n<p>constructor(width) {<\/p>\n<p>this.width = width;<\/p>\n<p>}<\/p>\n<p>area() {\u00a0\u00a0\u00a0\u00a0 return this.width ** 2;\u00a0 } };<\/p>\n<p>The module system is implemented in the require(&#8216;module&#8217;) module.<\/p>\n<h3>Accessing the main module<\/h3>\n<p>When a file is run directly from Node.js, require.main is set to its module. That means that it is possible to determine whether a file has been run directly by testing require.main === module. For a file foo.js, this will be true if run via node foo.js, but false if run by require(&#8216;.\/foo&#8217;).<\/p>\n<p>Because module provides a filename property (normally equivalent to __filename), the entry point of the current application can be obtained by checking require.main.filename.<\/p>\n<h3>Package Manager<\/h3>\n<p>The semantics of Node.js&#8217;s require() function were designed to be general enough to support a number of reasonable directory structures. Package manager programs such as dpkg, rpm, and npm will hopefully find it possible to build native packages from Node.js modules without modification.<\/p>\n<p>Below we give a suggested directory structure that could work:<\/p>\n<p>Let&#8217;s say that we wanted to have the folder at \/usr\/lib\/node\/&lt;some-package&gt;\/&lt;some-version&gt; hold the contents of a specific version of a package.<\/p>\n<p>Packages can depend on one another. In order to install package foo, it may be necessary to install a specific version of package bar. The bar package may itself have dependencies, and in some cases, these may even collide or form cyclic dependencies.<\/p>\n<p>Since Node.js looks up the realpath of any modules it loads (that is, resolves symlinks), and then looks for their dependencies in the node_modules folders as described here, this situation is very simple to resolve with the following architecture:<\/p>\n<ul>\n<li>\/usr\/lib\/node\/foo\/1.2.3\/ &#8211; Contents of the foo package, version 1.2.3.<\/li>\n<li>\/usr\/lib\/node\/bar\/4.3.2\/ &#8211; Contents of the bar package that foo depends on.<\/li>\n<li>\/usr\/lib\/node\/foo\/1.2.3\/node_modules\/bar &#8211; Symbolic link to \/usr\/lib\/node\/bar\/4.3.2\/.<\/li>\n<li>\/usr\/lib\/node\/bar\/4.3.2\/node_modules\/* &#8211; Symbolic links to the packages that bar depends on.<\/li>\n<\/ul>\n<p>Thus, even if a cycle is encountered, or if there are dependency conflicts, every module will be able to get a version of its dependency that it can use.<\/p>\n<p>When the code in the foo package does require(&#8216;bar&#8217;), it will get the version that is symlinked into \/usr\/lib\/node\/foo\/1.2.3\/node_modules\/bar. Then, when the code in the bar package calls require(&#8216;quux&#8217;), it&#8217;ll get the version that is symlinked into \/usr\/lib\/node\/bar\/4.3.2\/node_modules\/quux.<\/p>\n<p>Furthermore, to make the module lookup process even more optimal, rather than putting packages directly in \/usr\/lib\/node, we could put them in \/usr\/lib\/node_modules\/&lt;name&gt;\/&lt;version&gt;. Then Node.js will not bother looking for missing dependencies in \/usr\/node_modules or \/node_modules.<\/p>\n<p>In order to make modules available to the Node.js REPL, it might be useful to also add the \/usr\/lib\/node_modules folder to the $NODE_PATH environment variable. Since the module lookups using node_modules folders are all relative, and based on the real path of the files making the calls to require(), the packages themselves can be anywhere.<\/p>\n<p>To get the exact filename that will be loaded when require() is called, use the require.resolve() function. Putting together all of the above, here is the high-level algorithm in pseudocode of what require.resolve() does:<\/p>\n<p>require(X) from module at path Y<\/p>\n<ol>\n<li>If X is a core module,<\/li>\n<li>return the core module<\/li>\n<li>STOP<\/li>\n<li>If X begins with &#8216;\/&#8217;<\/li>\n<li>set Y to be the filesystem root<\/li>\n<li>If X begins with &#8216;.\/&#8217; or &#8216;\/&#8217; or &#8216;..\/&#8217;<\/li>\n<li>LOAD_AS_FILE(Y + X)<\/li>\n<li>LOAD_AS_DIRECTORY(Y + X)<\/li>\n<li>LOAD_NODE_MODULES(X, dirname(Y))<\/li>\n<li>THROW &#8220;not found&#8221;<\/li>\n<\/ol>\n<p>LOAD_AS_FILE(X)<\/p>\n<ol>\n<li>If X is a file, load X as JavaScript text. STOP<\/li>\n<li>If X.js is a file, load X.js as JavaScript text. STOP<\/li>\n<li>If X.json is a file, parse X.json to a JavaScript Object. STOP<\/li>\n<li>If X.node is a file, load X.node as binary addon. STOP<\/li>\n<\/ol>\n<p>LOAD_INDEX(X)<\/p>\n<ol>\n<li>If X\/index.js is a file, load X\/index.js as JavaScript text. STOP<\/li>\n<li>If X\/index.json is a file, parse X\/index.json to a JavaScript object. STOP<\/li>\n<li>If X\/index.node is a file, load X\/index.node as binary addon. STOP<\/li>\n<\/ol>\n<p>LOAD_AS_DIRECTORY(X)<\/p>\n<ol>\n<li>If X\/package.json is a file,<\/li>\n<li>Parse X\/package.json, and look for &#8220;main&#8221; field.<\/li>\n<li>let M = X + (json main field)<\/li>\n<li>LOAD_AS_FILE(M)<\/li>\n<li>LOAD_INDEX(M)<\/li>\n<li>LOAD_INDEX(X)<\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<p>LOAD_NODE_MODULES(X, START)<\/p>\n<ol>\n<li>let DIRS = NODE_MODULES_PATHS(START)<\/li>\n<li>for each DIR in DIRS:<\/li>\n<li>LOAD_AS_FILE(DIR\/X)<\/li>\n<li>LOAD_AS_DIRECTORY(DIR\/X)<\/li>\n<\/ol>\n<p>NODE_MODULES_PATHS(START)<\/p>\n<ol>\n<li>let PARTS = path split(START)<\/li>\n<li>let I = count of PARTS &#8211; 1<\/li>\n<li>let DIRS = [GLOBAL_FOLDERS]<\/li>\n<li>while I &gt;= 0,<\/li>\n<li>if PARTS[I] = &#8220;node_modules&#8221; CONTINUE<\/li>\n<li>DIR = path join(PARTS[0 .. I] + &#8220;node_modules&#8221;)<\/li>\n<li>DIRS = DIRS + DIR<\/li>\n<li>let I = I &#8211; 1<\/li>\n<li>return DIRS<\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>In the Node.js module system, each file is treated as a separate module. For example, consider a file named foo.js: const circle = require(&#8216;.\/circle.js&#8217;); console.log(`The area of a circle of radius 4 is ${circle.area(4)}`); On the first line, foo.js loads the module circle.js that is in the same directory as foo.js. Here are the contents&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"categories":[8453],"tags":[8327],"class_list":["post-72655","page","type-page","status-publish","hentry","category-node-js","tag-module-basics"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Module Basics - Tutorial<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Module Basics - Tutorial\" \/>\n<meta property=\"og:description\" content=\"In the Node.js module system, each file is treated as a separate module. For example, consider a file named foo.js: const circle = require(&#8216;.\/circle.js&#8217;); console.log(`The area of a circle of radius 4 is ${circle.area(4)}`); On the first line, foo.js loads the module circle.js that is in the same directory as foo.js. Here are the contents...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/\" \/>\n<meta property=\"og:site_name\" content=\"Tutorial\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/vskills.in\/\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-12T08:52:58+00:00\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/\",\"name\":\"Module Basics - Tutorial\",\"isPartOf\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\"},\"datePublished\":\"2020-01-14T11:03:36+00:00\",\"dateModified\":\"2024-04-12T08:52:58+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Module Basics\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"name\":\"Tutorial\",\"description\":\"Vskills - A initiative in elearning and certification\",\"publisher\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\",\"name\":\"Vskills\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"contentUrl\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"width\":73,\"height\":55,\"caption\":\"Vskills\"},\"image\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/vskills.in\/\",\"https:\/\/x.com\/vskills_in\",\"https:\/\/www.linkedin.com\/company-beta\/1371554\/\",\"https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Module Basics - Tutorial","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:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/","og_locale":"en_US","og_type":"article","og_title":"Module Basics - Tutorial","og_description":"In the Node.js module system, each file is treated as a separate module. For example, consider a file named foo.js: const circle = require(&#8216;.\/circle.js&#8217;); console.log(`The area of a circle of radius 4 is ${circle.area(4)}`); On the first line, foo.js loads the module circle.js that is in the same directory as foo.js. Here are the contents...","og_url":"https:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/","og_site_name":"Tutorial","article_publisher":"https:\/\/www.facebook.com\/vskills.in\/","article_modified_time":"2024-04-12T08:52:58+00:00","twitter_misc":{"Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/","name":"Module Basics - Tutorial","isPartOf":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website"},"datePublished":"2020-01-14T11:03:36+00:00","dateModified":"2024-04-12T08:52:58+00:00","breadcrumb":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/module-basics-2\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.vskills.in\/certification\/tutorial\/"},{"@type":"ListItem","position":2,"name":"Module Basics"}]},{"@type":"WebSite","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","name":"Tutorial","description":"Vskills - A initiative in elearning and certification","publisher":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization","name":"Vskills","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","contentUrl":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","width":73,"height":55,"caption":"Vskills"},"image":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/vskills.in\/","https:\/\/x.com\/vskills_in","https:\/\/www.linkedin.com\/company-beta\/1371554\/","https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw"]}]}},"_links":{"self":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/72655","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/comments?post=72655"}],"version-history":[{"count":3,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/72655\/revisions"}],"predecessor-version":[{"id":73160,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/72655\/revisions\/73160"}],"wp:attachment":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/media?parent=72655"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/categories?post=72655"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/tags?post=72655"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}