Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

346 CHAPTER 8 Websites and services


The following is a typical folder structure for creating a package. You start by creating a
root folder for your package.
\packageName
\bin
main.js
\lib
module1.js
module2.js
package.json
README.md

Inside the package root folder, you have a package.json file, which is the manifest file. You
also need a README.md file containing enough help to get the user started. In addition, you
need a bin folder and a lib folder. The bin folder contains the entry point to your package; the
lib folder contains the modules.
In this example, the package root folder is created at C:\node_samples\math_example;
math_example is the package name.
In the lib folder, the first module is created, called call_counter.js, which has the following
code.
var internal_call_counter=0;

function count_call(){
++internal_call_counter;
console.log('You have made ' + internal_call_counter + ' calls!');
}

module.exports = count_call;

It looks like the internal_call_counter variable and the count_call function are polluting the
global namespace, but this module code will be wrapped so that neither will be in the global
namespace. You can define what is available when a user uses the require(‘call_counter’)
function by assigning something to module.exports. In this case, the only exported function is
count_call, but you can specify multiple functions by wrapping them in an object, as you’ll see
in the simple_math.js and advanced_math.js modules.
The next module created in the lib folder is simple_math.js, which has the following code.
var call_counter = require('./call_counter');

function add(x, y){
call_counter();
return x + y;
}

function subtract(x, y){
call_counter();
return x - y;
}
Free download pdf