Join Alexander Zanfir for an in-depth discussion in this video Writing your own module, part of Up and Running with Node.js.
- 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, and we'll call this "my-module.js". And now let's create another file that will be using the module we'll be creating. We'll call it "module-demo.js". The idea is to get the code inside my-module.js to be accessible inside our "module-demo.js". The power behind that, is for example, this could be a math library that we've written, and we'd like to re-use it inside different files, or maybe even different projects.
This leverages the concept of code-reuse. So to continue, let's go over to "my-module.js" and we'll use the "exports" object, and we can pass in any data we 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", and the objective is to get this text inside our "module-demo". 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 it's reference to a variable, and I'll call that "myModule", and I'll use "require()" to bring it in.
I'll specify the filename and location. And now let's do a simple "console.log()" test, to see if we're getting the value from our module. So we'll access our module reference, and then we'll get the value from the property we created. Now, let's go over to our console or terminal. And we'll type in, "node module-demo.js" to execute the script.
And, as you can see, our test worked. We're getting the value from our module. Inside brackets, we can also get plugins which allow us to run Node within brackets. So, if I go over to the extension manager, I've installed a plugin called "Node.js bindings." And with that, I can hit Alt+N, and you can see that we're getting the value as we did inside our terminal or command prompt.
- Installing Node.js
- Writing modules and packages
- Reading and writing files
- Working with frameworks: Express, Sails, and Koa
- Generating promises
- Working with generator functions
Skill Level Beginner
Q: When I try to install Bluebird/Express/Gulp/Sails/KOA using the Node Package Manager, it seems to install correctly in the terminal. But why doesn't my project folder change?
A: You need to make sure that you've navigated to your project folder in the terminal. For example, in this course Alexander is working from the C:\Dev\ folder both in Brackets and in the terminal.