Node.js – Modules – A brief discussion

A module is nothing but a file in Node.js. Yes, what you read is correct. For example, if you write your own code in a file; sample.js, Node.js treats this one as a module.

If you want to use the code written in your file in another file or module; you need to use require method to include the file or module in another file or module.

The functions or methods written in the module will be exported to use into another modules. When you define the methods or members as private, they can not be exported and not allowed to use in another modules. Private members are private to the module.

Node.js provides built-in modules and these we can call as Core Modules; these are defined within Node.js‘s source and you can find these Core Modules in lib/ folder.

Core modules have the priority than the user-defined modules. That means, if you have written your own module with the same name as Core Module name; Node.js will load the Core Module instead of the User-defined module, when you attempt to load them using require method.

When you want to use user-defined modules, you can use either relative paths or absolute paths in require method to load them into another modules. Absolute path starts with back-slash “/” and relative path starts with “./”. For example; “/root-dir/sub-dir/module-name.js” or “./module-name.js”.

After the module is loaded; Node.js will wrap the module code within the function and execute the module code. This way, it achieves few benefits. For example, the variables defined in the module will be scoped to the module instead of scoped to the global scope.

Before we close this Article, just would like to mention module object; which is a reference to the current module.

</> Michael

Node.js – Modules – A brief discussion

One thought on “Node.js – Modules – A brief discussion

Leave a Reply

Your email address will not be published.

Scroll to top