Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

348 CHAPTER 8 Websites and services


In the advanced_math.js file, the require function also references the call_counter.js mod-
ule. The multiply, divide, and fibo functions call the call_counter variable, which references the
count_call function. The advanced_math.js module exports three functions, so an object is
created to provide access to these functions.
The fibo function calls the private_fibo function, a recursive function that calls itself until
the count and counter are equal. The private_fibo function is not exported, so it will be acces-
sible only from the fibo function that is exported.

Creating an aggregate module
After the modules are created, you might want to expose a single object with the items that
are exported across all the modules. Exposing a single object makes it easier for your pack-
age users to access the features of your package. This is the entry point module, which is an
aggregate of the other modules in your package.
In the bin folder, create a main.js module that contains the following code.
var path = require('path');
var fs = require('fs');
var lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib');
var simple = require(lib + '/simple_math.js');
var advanced = require(lib + '/advanced_math.js');
module.exports = {
addition: simple.addition,
subtraction: simple.subtraction,
multiplication: advanced.multiplication,
division: advanced.division,
fibonacci: advanced.fibonacci
}

This module first references two built-in node.js packages, path and fs. These packages are
helpers that get the path to the lib folder. Next, references to simple_math.js and advanced_
math.js are created using this path to the lib. The call_counter.js module is not referenced
because the package uses it but does not expose it. Finally, module.exports is assigned an
object in which the functions that were exposed on simple_math.js and advanced_math.js are
now exported by the package.

Creating the README.md file
The README.md file contains enough help to get the user started with your package. The
file extension of .md denotes a Markdown file. A Markdown file is a simple way of providing
formatting on a text document so it can be displayed nicely as text or in a browser. A quick
search on the web for markdown language will yield numerous articles and free Markdown
editors, such as MarkdownPad, as shown in Figure 8-3. The contents of the README.md file
are as follows.
math_example package
====================

Key
Te rms
Free download pdf