In the previous article, we have discussed some basics of node.js and its benefits in web development, so in this tutorial, we will talk about the Node Module System.
If you are new to node please check our previous article on Node.js to better understand of Node.js.
So let’s get started…
What is Node.js Module system?
Every ﬁle in a Node application is a module, and every variable and functions defined in that function or module are scopes to that particular file, with using modularity system we can create small building blocks or modules where we can define our variables and functions.
so two variable and functions with the same name don’t override a variable or function defined somewhere else. because they are encapsulated inside of that module or in object-oriented programming terms we can say they are private and not accessible outside of it.
To make it available outside of it you need to export it and make it public
Every Node Application has at least one file or one module which we call the main module
Node automatically wraps the code in each ﬁle with an IIFE (Immediately-invoked Function Expression) to create scope So, variables and functions deﬁned in one ﬁle are only scoped to that ﬁle and not visible to other ﬁles unless explicitly exported
To export a variable or function from a module, you need to add them to module.exports:
module.exports.sayHello = sayHello
To load a module, use the require function. this function returns the module.exports object exported from the target module:
const logger = require(‘./log’);
How to create a module in node.js?
1 : Create a userData.js file and paste the following code:
module.exports.log = log;
How to load the module?
2 :Then Create an app.js file which we call main module file and paste the following code:
//use require method to call modules
const userData = require('./userData');
//now we can use userData const to access module
that’s it, now go to terminal and type
$node app.js // it will return alexa as result
So, that’s how we can create the custom module in node.js.
- Getting Started With Node.js : A Begginers Guide
- Hello world in Node.js with Express Framework
- NPM Novice to Ninja guide – NPM Tutorial
Node has also a few built-in modules that enable us to work with the ﬁle system, path objects, network, operating system, etc that we will learn in the next article.
Thanks for reading. in this post, we have covered some basic introduction of node js module system.
Do let me know If you face any difficulties please feel free to comment below we love to help you. if you have any feedback suggestions then please inform us by commenting.