CHAPTER 7
In the previous chapter, we learned about functions. We can create a function and call it in our code. Now, we’re going to learn about modules.
Consider you have a function. You want to call this function in many files. The simple solution is to write this function to each *.js file. If you change it, you must change it in all *.js files. For this situation, we need a module. We write a function once in a module. Then, it will be called by attaching this module.
We can create a simple function and then it will be exported as a module.
Let’s write the code:
var calculate = function(numA,numB){ return numA*numB + 10*numB; } exports.calculate = calculate; |
You can see that we can use exports to expose our functions. Save this code into a file, called MyModule.js.
To call this module from our code, we can use require.
var myModule = require('./MyModule.js'); var result = myModule.calculate(20,10); console.log(result); |
require needs the full path of the module. ‘./’ means the module has the same location with the caller. Save this code into a file called testModule.js. Run it:
node testModule.js |
The program output of the application can be seen in Figure 45.

Figure 45: Consuming module in Node.js
You also can create many functions to be exported in the module. Here is sample code:
var calculate = function(numA,numB){ return numA*numB + 10*numB; } var add = function(numA,numB){ return numA + numB; } var perform = function(){ // do something } exports.calculate = calculate; exports.add = add; exports.perform = perform; |
If you have experiences in object-oriented programming, you may implement a class in Node.js. Of course, you can create a class as a module in Node.js.
For instance, we create a class, called Account. First, create a file called Account.js and write this code:
// constructor var Account = module.exports = function(){ console.log('constructor'); } // method Account.prototype.perform = function(){ console.log('perform'); } // method Account.prototype.foo = function(a,b){ console.log('foo - ' + a + '-' + b); } |
We expose our class using module.exports. Then we implement class methods using prototype.
Now we test this class.
Let’s write this:
var Account = require('./Account.js'); var account = new Account(); account.perform(); |
You can see that we need to instantiate our object by calling new Account().Save this code into a file called testAccount.js. Run it:
node testAccount.js |
The sample of program output can be seen in Figure 46.

Figure 46: Implementing class in a module