|
| 1 | +<!DOCTYPE html> |
| 2 | +<html> |
| 3 | + |
| 4 | +<head> |
| 5 | + <meta http-equiv="content-type" content="text/html; charset=utf-8"> |
| 6 | +<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1"> |
| 7 | +<title> Explained: What are Node.js modules? · The Node Beginner Blog </title> |
| 8 | + |
| 9 | + |
| 10 | +<link rel="stylesheet" href="https://www.nodebeginner.org/blog/css/slim.css"> |
| 11 | +<link rel="stylesheet" href="https://www.nodebeginner.org/blog/css/highlight.min.css"> |
| 12 | +<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700|Source+Code+Pro' rel='stylesheet' type='text/css'> |
| 13 | + |
| 14 | +<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/apple-touch-icon-144-precomposed.png"> |
| 15 | +<link rel="shortcut icon" href="/favicon.ico"> |
| 16 | + |
| 17 | + |
| 18 | +<link href="" rel="alternate" type="application/rss+xml" title="The Node Beginner Blog" /> |
| 19 | + |
| 20 | +</head> |
| 21 | + |
| 22 | +<body> |
| 23 | + <div class="container"> |
| 24 | + <div class="header"> |
| 25 | + <h1 class="site-title"><a href="https://www.nodebeginner.org/blog/">The Node Beginner Blog</a></h1> |
| 26 | + <p class="site-tagline">Node.js tutorials, how-to's, and more.</p> |
| 27 | + |
| 28 | + |
| 29 | +</div> |
| 30 | + <div class="content"> |
| 31 | + <div class="posts"> |
| 32 | + <div class="post"> |
| 33 | + <h2 class="post-title"><a href="https://www.nodebeginner.org/blog/post/nodejs-tutorial-what-are-node.js-modules/">Explained: What are Node.js modules?</a></h2> |
| 34 | + <span class="post-date">Jul 5, 2017 </span> |
| 35 | + <div class="post-content"> |
| 36 | + <p>When you write Node.js applications, you could actually put all your code into one huge <em>index.js</em> file, no matter |
| 37 | +how large or complex your application is. The Node.js interpreter doesn’t care. But in terms of code organization, |
| 38 | +you would end up with a hard to understand and hard to debug mess quite quickly. So as a human being, you should care |
| 39 | +about how to structure your code. This is where modules come in. </p> |
| 40 | + |
| 41 | +<p>You can think of Node.js modules as JavaScript libraries - a certain part of your overall codebase (for example, a |
| 42 | +collection of functions) which you want to keep together, but which you also want to keep separated from the rest of |
| 43 | +your codebase to keep things cleanly separated.</p> |
| 44 | + |
| 45 | +<p>Just like we keep our socks in one drawer and our shirts in another drawer in our wardrobe - even if we combine |
| 46 | +both to create an outfit for the day - we can keep different parts of our codebase in different modules and then combine |
| 47 | +them into a coherent application.</p> |
| 48 | + |
| 49 | +<h2 id="built-in-modules">Built-in Modules</h2> |
| 50 | + |
| 51 | +<p>Even if we don’t create any Node.js modules ourselves, we already have modules at our disposal because the Node.js |
| 52 | +environment provides built-in modules for us. We already encountered one of these modules in this blog when we looked at |
| 53 | +<a href="/blog/post/nodejs-tutorial-whatwg-url-parser/">how to use the built-in WHATWG URL parser</a>.</p> |
| 54 | + |
| 55 | +<p>Within our own code file, we needed to use existing code which was declared elsewhere - in this case, the <code>URL</code> class |
| 56 | +which is part of the built-in Node.js module <code>url</code>:</p> |
| 57 | + |
| 58 | +<pre><code>var URL = require('url').URL; |
| 59 | +</code></pre> |
| 60 | + |
| 61 | +<p>The <code>require('url')</code> part is what gives us access to the code of the <code>url</code> module. Where and how this module is defined |
| 62 | +is completely opaque for us - all we need to know is its name - <code>url</code> - and the attributes it exposes, like <code>URL</code>.</p> |
| 63 | + |
| 64 | +<p>Other built-in modules directly expose the attribute we need (which often are JavaScript objects). The <code>http</code> module is |
| 65 | +an example:</p> |
| 66 | + |
| 67 | +<pre><code>var http = require('http'); |
| 68 | + |
| 69 | +http.createServer(function (req, res) { |
| 70 | + res.writeHead(200, {'Content-Type': 'text/html'}); |
| 71 | + res.end('Hello World!'); |
| 72 | +}).listen(8080); |
| 73 | +</code></pre> |
| 74 | + |
| 75 | +<p>Here, requiring the <code>http</code> module gives us direct access to an <code>http</code> object, whose methods, like <code>createServer</code>, we can |
| 76 | +then use.</p> |
| 77 | + |
| 78 | +<p><strong>The Node Beginner Book</strong> explains <a href="https://www.nodebeginner.org/">how to write a complete web server with Node.js</a> |
| 79 | +using the built-in <code>http</code> module.</p> |
| 80 | + |
| 81 | +<h2 id="external-modules">External Modules</h2> |
| 82 | + |
| 83 | +<p>The built-in modules which ship with Node.js allow to solve a lot of coding problems without reinventing the wheel for |
| 84 | +every new application, but what really boosts Node.js programming productivity is the huge ecosystem of open source |
| 85 | +modules provided by the Node.js community. These modules can be integrated into our codebase, too, but because they are |
| 86 | +not built-in and don’t ship directly with each installation of Node.js, it is not enough to <code>require</code> them from our own |
| 87 | +code. We need to install the codebase containing the external module locally first, which is made very easy thanks to |
| 88 | +<em>NPM</em>, the Node Package Manager.</p> |
| 89 | + |
| 90 | +<p>See this blog post which describes |
| 91 | +<a href="/blog/post/nodejs-tutorial-optimizing-code-performance-using-async/">how to use the <em>async</em> library</a> for an |
| 92 | +example of how to use external modules.</p> |
| 93 | + |
| 94 | +<p>Also, <strong>The Node Craftsman Book</strong> has a chapter on the details of |
| 95 | +<a href="https://leanpub.com/b/node-beginner-and-craftsman-bundle">working with NPM</a>.</p> |
| 96 | + |
| 97 | +<h2 id="creating-your-own-modules">Creating your own modules</h2> |
| 98 | + |
| 99 | +<p>Built-in and external modules are provided by others, but nothing stops you from creating your own Node.js modules.</p> |
| 100 | + |
| 101 | +<p>The following example creates a module <code>myRandom</code> which provides a helper function that returns random number between 1 |
| 102 | +and 10:</p> |
| 103 | + |
| 104 | +<p>File <code>myRandom.js</code>:</p> |
| 105 | + |
| 106 | +<pre><code>function getRandom(min, max) { |
| 107 | + return Math.random() * (max - min) + min; |
| 108 | +} |
| 109 | + |
| 110 | +exports.between1and10 = function() { |
| 111 | + return getRandom(1, 10); |
| 112 | +}; |
| 113 | +</code></pre> |
| 114 | + |
| 115 | +<p>You would put this code into it’s own file called <code>myRandom.js</code>. Because this file exists and provides attributes to the |
| 116 | +outer world via <code>exports</code>, another file <code>index.js</code> can use the exported functionality:</p> |
| 117 | + |
| 118 | +<p>File <code>index.js</code>:</p> |
| 119 | + |
| 120 | +<pre><code>var myRandom = require('./myRandom.js'); |
| 121 | + |
| 122 | +console.log(myRandom.between1and10()); |
| 123 | +</code></pre> |
| 124 | + |
| 125 | +<p>Again, <code>require</code> comes into play, making the exported attributes of the local <code>myRandom</code> module available - in this |
| 126 | +case, the <code>between1and10</code> function.</p> |
| 127 | + |
| 128 | +<p>Note: While the module system allows to <em>expose</em> functionality of a module, it also allows to <em>hide</em> functionality which |
| 129 | +is not needed outside of the module, simply by not exporting the functionality via <code>export</code>. Even though the <code>index.js</code> |
| 130 | +file has required the <code>myRandom.js</code> file, it cannot access the non-exported <code>getRandom</code> function:</p> |
| 131 | + |
| 132 | +<pre><code>var myRandom = require('./myRandom.js'); |
| 133 | + |
| 134 | +console.log(myRandom.getRandom(5, 99)); |
| 135 | +</code></pre> |
| 136 | + |
| 137 | +<p>will result in a <code>TypeError: myRandom.getRandom is not a function</code>.</p> |
| 138 | + |
| 139 | +<p>By hiding implementation details in a module and only exposing those parts which are to be used by other parts of your |
| 140 | +codebase, you can keep your codebase well organized.</p> |
| 141 | + |
| 142 | +<hr /> |
| 143 | + |
| 144 | +<p>Learn more about working with modules and <a href="https://www.nodebeginner.org/#a-basic-http-server">building your own web server</a> |
| 145 | +application with Node.js with <strong>The Node Beginner Book</strong> - the first part of this |
| 146 | +<a href="https://www.nodebeginner.org/">step-by-step Node.js tutorial</a> is available for free!</p> |
| 147 | + </div> |
| 148 | + </div> |
| 149 | + <div class="pagination"> |
| 150 | + |
| 151 | + |
| 152 | + <a class="btn previous " href="https://www.nodebeginner.org/blog/post/nodejs-tutorial-optimizing-code-performance-using-async/">Prev</a> |
| 153 | + |
| 154 | + </div> |
| 155 | + </div> |
| 156 | + </div> |
| 157 | + |
| 158 | + <div class="footer"> |
| 159 | + |
| 160 | + <p>Copyright (c) 2017 Manuel Kiessling</p> |
| 161 | + |
| 162 | +</div> |
| 163 | + |
| 164 | + </div> |
| 165 | + <script src="https://www.nodebeginner.org/blog/js/slim.js"></script> |
| 166 | + <script src="https://www.nodebeginner.org/blog/js/highlight.min.js"></script> |
| 167 | + <script> |
| 168 | + hljs.initHighlightingOnLoad(); |
| 169 | + </script> |
| 170 | + <script> |
| 171 | +(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ |
| 172 | +(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), |
| 173 | +m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) |
| 174 | +})(window,document,'script','//www.google-analytics.com/analytics.js','ga'); |
| 175 | + |
| 176 | +ga('create', 'UA-2127388-6', 'auto'); |
| 177 | +ga('send', 'pageview'); |
| 178 | + |
| 179 | +</script> |
| 180 | + |
| 181 | +</body> |
| 182 | + |
| 183 | +</html> |
0 commit comments