The module system

In an effort to make the code as modular and reusable as possible, Node uses a module system that allows you to better organize your code. The basic premise is that you write a code fulfilling a single concern, and export this code using module.exports (or simply exports) as a module that serves that single purpose. Whenever you need to use that code elsewhere in your code base, you will require that module:

// ** file: dowork.js 
module.exports = { 
  doWork: function(param1, param2) { 
    return param1 + param2; 
  }   
} 
 
// ** file: testing.js 
var worker = require('./dowork'); // note: no .js in the file 
 
var something = 1; 
var somethingElse = 2; 
 
var newVal = worker.doWork(something, somethingElse); 
console.log(newVal); 
// => 3 

Using this system, it is simple to reuse the functionality in a module (in this case, the dowork module) in a number of other files. Furthermore, the individual files of a module act as a private namespace, which means every file defines a module and is executed separately. Any variables declared and used within the module file are private to that module and not exposed to any code that uses the module via require(). The developer has control over which part of module will be exported or not. Such implementation of modules is called as the commonJs modules pattern.

Before we conclude module system in Node.js, we need to learn about the require keyword. The require keyword accepts an address of a file as string and provides it to JavaScript engine to compile it into a method Module._load. The Module._load method is executed for first time, it actually loads from the exported file and further it is cached. Caching is done so as to reduce the number of file reads and can speed up your application significantly. In addition, when a module is loaded next time, it provides an instance of that loaded module from cache. This allows sharing of modules across the project with the state of singleton. At the end, the Module._load method returns the module.exports property of the addressed file on their respective execution.

The module system extends infinitely as well. Within your modules, you can require other modules and so on and so forth. Make sure while importing it, do not cause so called a cyclic dependency.

Cyclic or circular dependency is a situation when a module requires itself directly or indirectly. We can learn about this more from the discussion in the following link :
https://stackoverflow.com/questions/10869276/how-to-deal-with-cyclic-dependencies-in-node-js.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.97.40