Join Alexander Zanfir for an in-depth discussion in this video Write your own module, part of Learning Node.js.
- [Instructor] Now let's take a look at how modules work inside node.js. We'll dive right in and start creating our own. Let's create a new file. So in Visual Studio code, I'll hit the new file icon and we'll call this my-module.js. And now let's create another file that we'll be using our new module. I'll call it module-demo.js. The idea is to get the code inside my module to be accessible inside our module demo. The power behind that, for example, this could be a math library that we've written and we'd like to reuse it inside different files or maybe even inside different projects.
This leverages the concept of code reuse. So to continue, let's go over to my module and we'll use the exports object and we can pass in any data we'd like with exports. We'll create a property called myText and we'll set that to some placeholder value. I'll set it to hello from module. (keys clicking on keyboard) Node has a simple module loading system. In Node, files and modules are in a one to one correspondence and in order to access my module, I'll first set its reference to a variable.
So let's go in our module demo and I'll call this variable myModule. And I'll use require to bring it in. (keys clicking on keyboard) And then I'll specify the path. (keys clicking on keyboard) And now to test this, let's do a simple console log in the line below. We'll test to see if we're getting the same value from our module. So we'll access our module reference with myModule and then we'll get the value from the property we created, .myText.
Now let's go over to our console or terminal and execute our module demo. So I'll type in node and then the file name module demo. And as we can see, we're getting our console log with the hello from module placeholder text. And so we were able to access data in our module demo from another module or file. We'll be able to do the same thing with functionality later on.
- Asynchronous tasks and callbacks
- Managing third-party packages with npm
- Node.js frameworks
- Static serving with Express
- Creating a browser app
- Exploring databases
- Saving data to MongoDB with Mongoose
- Error handling and debugging
- Simple tests and async tests