Creating, Exporting and Loading Modules in Node

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?

One of the disadvantages of JavaScript is the global namespace sharing amongst different scrips. This is caused by the fact that when you load one or more JavaScript files/code, it is injected to one global namespace and thus if you had defined one global variable on one file, and the same in the other file, this will confict and create all sorts of bugs. This is where node helps in fixing this issue. Node used CommonJS to standardize packaging of JavaScript Libraries, called modules. Each module has its own context and does not conflict or interfere with other modules which eliminates the use of one global namespace by exposing a public API that can be used any time after importation.

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.

Continue reading