Skip to content

Latest commit

 

History

History
141 lines (93 loc) · 5.91 KB

File metadata and controls

141 lines (93 loc) · 5.91 KB
layout post
title Using and Creating Modules
author NodeKC
tags

Using and Creating Modules

In the last few labs, you used require() to import the fs and http core modules. Now let's see how require works and create a module of our own.

How do modules work?

In Node.js, modules work by exporting methods or values. If this were visualized in JavaScript it might be similar to this:

{% highlight javascript %} var exports = {};

(function() { var a = 10;

exports.foo = a * 10; })();

console.log(exports.a); // undefined console.log(exports.foo); // 100 {% endhighlight %}

Notice the (function () { /* module code here */ } )();. This provides a new scope for the module to prevent pollution of the global object. In JavaScript, this is known as a closure.

Modules in Node.js are executed within their own scope (therefore, the outer closure isn't necessary). If written into a Node.js module, the same code sample would be written as:

{% highlight javascript %} var a = 10;

exports.foo = a * 10; {% endhighlight %}

Before we get much further, it's important to note that the exports and module.exports objects in Node.js are equivalent. They are both available because one conforms to the CommonJS standard and the other to the RequireJS standard.

Create and require a module

First create a folder called shapes. Inside of shapes, create a file called circle.js with the following contents:

{% highlight javascript %} var PI = Math.PI;

exports.area = function (r) { return PI * r * r; };

exports.circumference = function (r) { return 2 * PI * r; }; {% endhighlight %}

The module circle.js has exported the functions area() and circumference(). To export an object, add to the special exports object. Variables local to the module will be private. In this example, the variable PI is private to circle.js.

Next, add another file to shapes called circle_example.js with the following contents:

{% highlight javascript %} var circle = require('./circle'); var radius = 10; console.log('The area of a circle with radius ' + radius + ' is ' + circle.area(radius)); {% endhighlight %}

Now, run the app by typing node circle_example.js from within the shapes directory. You should see the following:

{% highlight bash %} The area of a circle with radius 10 is 314.159265359 {% endhighlight %}

Note the use of ./ in require('./circle.js') - if the module name starts with this Node will load the a file relative to the current working directory. Omitting the ./ would instruct Node to look in node_modules or within Nodes core modules.

On your own try to create a rectangle module with similar operations.

Require a JSON file

A JSON file can be included in a project by doing a require('./filename.json'). This is because .json files are parsed as JSON text files automatically.

Let's create an example of a JSON configuration file. To begin, create a a file called config.json with the following contents:

{% highlight javascript %} { "poll-frequency": 10, "urls": ["test.com", "test.org"], "data": { "name": "test", "encoding": "utf8" } } {% endhighlight %}

Now, let's open a Node REPL and see how the module system loads JSON files. Notice that what's returned by require is a JavaScript object that resembles the contents of config.json. Once again, it's important to remember the ./ prefix when requiring local files. If you omit the prefix Node will assume you're looking to load something from the node_modules directory or from Node's core modules.

{% highlight javascript %}

var config = require('./config') undefined config.urls [ 'test.com', 'test.org' ] {% endhighlight %}

Require a core module

Node.js ships with several modules to perform various system operations. The core modules are defined in Node.js's source in the lib folder.

Core modules are always preferentially loaded if their file name is passed to require(). For instance, require('http') will always return the built in HTTP module, even if there is a file or npm module by that name.

Require a module from the node_modules directory

Modules can be installed using the Node.js package manager npm to be included into your application.

For the next example, let's take a list of numbers and sort and filter them. To do this, include the underscore.js module. First we need to install underscore by executing the following command from a brand new directory.

{% highlight bash %} $ npm init /* fill out the defaults */ $ npm install underscore --save {% endhighlight %}

Now create a file called sort_example.js and add the following:

{% highlight javascript %} var underscore = require('underscore');

var listOfNumbers = [1,5,4,3,7,6];

var sortedList = underscore.sortBy(listOfNumbers, function (n) { return n; });

console.log(sortedList); {% endhighlight %}

After you've mastered how to use modules and create them you can learn to publish publicly at the npm website.

Module caching

Node automatically caches required modules based on the full OS path to that module. This has a few side effects. First, each module will ever only be loaded once from a given directory. That means any modifications to the exported functions, objects, or internal state will be available to all users of that module in your application. Secondly, you can load different versions of the same module based upon where it's being loaded from. This can be very nice when some of your dependencies use a different version of underscore for example.