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.