A module is a small component or building block of an application. A module consists of variables and functions. With respect to a node application, every file is considered to be a module.
The variables and functions defined in a module are scoped to that module(or file) only. In order to use the variables and functions of a module, they need to be exported.
Thus, a file named firstprogram.js is a module in node.
Benefits of a module
Following are the advantages of a module.
Encapsulation: A module consists of variables and functions written inside a file. These cannot be accessed from another file if they are not exported.
Reusability: A module once written can be easily distributed or imported in another modules. Thus, the functionality written in a module can be re-used in another module when required.
Security: There are two aspects of security when using modules. First, variables and functions written inside a module cannot be accessed or modified if not exported. Second, there is no risk of variables and functions with same name in an application being overwritten since they are distinguished by modules.
Node Module object
Node provides a
module object which represents a module. This
module object is available in every module(or file) and contains information about that module. Thus, create a file named firstprogram.js and print
module object using
console.log(module). If you are not sure how to do this, check it out here.
You will see the below output.
paths: [ ‘E:\\node\\node_modules’, ‘E:\\node_modules’ ] }
As you can see from the above output, it shows the name of file, its path etc.0