06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 9<br />

Creating modules<br />

Node modules can be either single files or directories containing one or more files.<br />

It's usually a good idea to create a separate module directory. The file in the module<br />

directory that will be evaluated is normally named index.js. A module directory<br />

can look as follows:<br />

node_project/src/nav<br />

--- >index.js<br />

In your project directory, the nav module directory contains the module code.<br />

Conventionally, your module code needs to reside in the index.js file—you can<br />

change this to another file if you want. Consider this trivial module called geo.js:<br />

exports.area = function (r) {<br />

return 3.14 * r * r;<br />

};<br />

exports.circumference = function (r) {<br />

return 3.14 * 3.14 * r;<br />

};<br />

You are exporting two functions via exports. You can use the module using the<br />

require function. This function takes the name of the module or system path to the<br />

module's code. You can use the module that we created as follows:<br />

var geo = require('./geo.js');<br />

console.log(geo.area(2));<br />

As we are exporting only two functions to the outside world, everything else<br />

remains private. If you recollect, we discussed the module pattern in detail—Node<br />

uses CommonJS modules. There is an alternative syntax to create modules as well.<br />

You can use modules.exports to export your modules. Indeed, exports is a helper<br />

created for modules.exports. When you use exports, it attaches the exported<br />

properties of a module to modules.exports. However, if modules.exports already<br />

has some properties attached to it, properties attached by exports are ignored.<br />

[ 213 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!