In this post we will cover the basics of what Modules are, how to create modules, export modules and require (reference) a module. If you are already aware of what Modules are, you can skip the first part and jump straight away to the hands on examples.
What are Modules?
A Module can be classified either as a Core Module, File Module, Folder Module or a third-party Module.
- Core Modules expose some Node core functions that a programmer needs which are preloaed when a Node process starts. When referencing a Core Module, only the module name is used.
- A file or folder module, are modules created by the programmer himself or others around him and are referenced by the file path or by file name. When referencing a module by file name, it will automatically map it into a file path, taking the assumption it is in the current file path.
- A folder module can be referenced by the folder path without the filename and node will assume this folder is a package. Thus, node will look for a package definition in json format with the name package.json and if not found it sets the default file value of index.js.
- Third-party Modules are modules available to download and install. Installing third-party modules is made easy through the NPM (Node Package Manager) and are referenced by module name.
Creating and Exporting Modules
Write a function as needed, in this case i will create a simple Math function to demonstrate how Node Modules work:
console.log(Math.round(3 * 3));
console.log(Math.round(5 * 5));
module.exports.five_squared = five_squared;
Note: Look at the last two lines. There we are defining what is to be exported by the module. We can have one or more module exports, in face here we have two different exports. “module” is a variable that represents the current module the programmer is in, while “module.export” is the object that the module will export to other scripts who require this module.
To reference a module, the require function is used as follows:
var myCoreModule = require('http');
var myFileModule = require('../testingModules/myModule'); //equivalent to var myFileModule = require('../testingModules/myModule.js');
var myFolderModule = require('../testingModules');
var myModule = require('./myFirstModule');
Running test.js on Node
Open the cmd (command-line):
- change directory to the folder “testingModules” (to change directory type cd following the path)
- type “node test.js” and enter.
This should give print 3 squared (9) on one line and 5 squared (25) on another line as shown below:
Here we learned how to create, export and also loading modules, hope all was clear 🙂