What Is NodeJS Module

Before moving to this article, please read my previous article:

  • Introduction To NodeJS
In continuation to the article Introduction to node.js this article focuses on node js modules.

A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file. Node modules run in their own scope so that they do not conflict with other modules. Node relatedly provides access to some global to help facilitate module interoperability. The primary 2 items that we are concerned with here are require and exports. You require other modules that you wish to use in your code and your module exports anything that should be exposed publicly. Lets see an example : save the below code as test.js,
  1. exports.name = function() {  
  2. console.log('My name is Sourav Lahoti');  
  3. };  
which you call from another file thus:
  1. var test= require('./test.js');  
  2. test.name(); // 'My name is Sourav Lahoti  
So in this example we see we use exports keyword to define a module that would be imported by another js file as in case of test.

Difference Between module.exports and exports

You can use both exports and module.exports to import code into your application like this:
  1. var mycode = require('./path/to/mycode');  
The basic use case you'll see (e.g. in ExpressJS example code) is that you set properties on the exports object in a .js file that you then import using require()

So in a simple counting example, you could have:
  1. (counter.js)  
  2.   
  3. var count = 1;  
  4.   
  5. exports.increment = function() {  
  6. count++;  
  7. };  
  8.   
  9. exports.getCount = function() {  
  10. return count;  
  11. };  
  12. .. then in your application (any other .js file):  
  13.   
  14. var counting = require('./counter.js');  
  15. console.log(counting.getCount()); // 1  
  16. counting.increment();  
  17. console.log(counting.getCount()); // 2  
In simple terms, you can think of required files as functions that return a single object, and you can add properties (strings, numbers, arrays, functions, anything) to the object that's returned by setting them on exports.

Sometimes you'll want the object returned from a require() call to be a function you can call, rather than just an object with properties. In that case you need to also set module.exports, like this:

(hello.js):
  1. module.exports = exports = function() {  
  2. console.log("Hello World!");  
  3. };  
(app.js):
  1. var Hello = require('./hello.js');  
  2. Hello(); // "Hello World!"  
So we have touch about node modules and how it is used in node.js . In next article we will touch upon npm (node package manager and why is it used for).

Read more articles on NodeJS:


Similar Articles