Implementing Modules in Node

#BuildTogether Day70/100

Today was Lego day 😍. I bought this expensive Art Project from Copenhagen Aiport on my way back to Dublin (Yes, it is cheaper on Amazon 😏) Today, I decided to open it and it was awesome.. ❤️ It was #buildTogether with my husband ;)

Fun with Legos

Now let’s talk Modules :D

What are Modules?

Modules are reusable pieces of code in a file that can be exported and then imported for use in another file. A modular program is one whose components can be separated, used individually, and recombined to create a complex system.

myApp.js with separate modules

The above diagram illustrates breaking down of the entire program within myApp.js into separate components that each handle a particular task like database, server operations, and date value conversions.

The modular strategy is termed as separation of concerns and is useful for many reasons:

  • find, fix, and debug code more easily.
  • reuse and recycle defined logic in different parts of the application.
  • keep information private and protected from other modules.
  • prevent pollution of the global namespace and potential naming collisions, by cautiously selecting variables and behavior loaded into a program.

Implementing modules in a program requires management via the following :

  • To use the Node.js module.exports object to export code from a file - meaning its functions and/or data can be used by other files/modules.
  • To use the Node.js require() function to import functions and/or data from another module.

Implementation of Modules in JavaScript: Node.js vs ES6

There are multiple ways of implementing modules depending on the runtime environment in which the code is executed. In JavaScript, there are two runtime environments and each has a preferred module implementation:

  1. The Node runtime environment and the module.exports and require() syntax.
  2. The browser’s runtime environment and the ES6 import/export syntax.

This article focuses on using the module.exports and require() syntax in the Node runtime environment.

Modules in Node

Every JavaScript file that runs in a Node environment is treated as a distinct module. The functions and data defined within each module can be used by any other module, as long as those resources are properly exported and imported.

Consider following two programs that use the same function celsiusToFahrenheit and is writing twice.

Program 01

Executing the above code would be like:

$ node temperatures.js
The freezing point of water in Fahrenheit is 32
The boiling point of water in Fahrenheit is 212

Program 02

Executing this code will give the below response:

$ node celsius-to-fahrenheit.js 100
100 degrees Celsius = 212 degrees Fahrenheit

Creating a module that exports a celsiusToFahrenheit() function that can be used by both of these programs would solve this repetitive code problem.

module.exports

To create a module, the same function is declared in a new file. Then, to make this function available to other files, its added as properties to the built-in module.exports object:

Two approaches are depicted, one is to assign an already-defined function to module.exports.celsiusToFahrenheit. In the second, a new function expression is declared and assigned to module.exports.fahrenheitToCelsius doing the opposite conversion.

module.exports object is built into the Node.js runtime environment. Other files can import this object, with another feature built into the Node.js runtime environment: the require() function, and make use of these two functions.

require()

The require() function accepts a string as an argument. That string provides the file path to the module you would like to import.

Let’s update temperatures.js such that it uses require() to import the .celsiusToFahrenheit() method from the module.exports object within converters.js:

In this case, ./ is a relative path indicating that converters.js is stored in the same folder as temperatures.js. Using require(), the entire module.exports object is returned and stored in the variable converters. This means that both the .celsiusToFahrenheit() and .fahrenheitToCelsius() methods can be used in this program.

Using Object Destructuring for selective exports with require()

In many cases, modules export a large number of functions but only one or two of them are needed. Object destructuring can be used to extract only the needed functions.

The program works the same way but the program avoids importing a function it does not need.

That is all today :D. If you fancy seeing my #100Days journey, please drop by

--

--

--

Technical Speaker and an aspiring writer with avid addiction to gadgets, meet-up groups, Kotlin and paper crafts.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

React spread attributes — Don’t overuse them.

JavaScript Some Awesome Features.

React Notes

JS — Promise executor

Evolution of Type Checking for JavaScript Apps in Vendavo

JavaScript Fundamentals: Using Conditionals

The power of WebSockets

UI Testing in React Native with Detox

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Henna Singh

Henna Singh

Technical Speaker and an aspiring writer with avid addiction to gadgets, meet-up groups, Kotlin and paper crafts.

More from Medium

Deploy Node JS + React Js Application on Virtual Machine (Server)

FIREBASE & REACT: Setting Up React APP with Firebase

coverImage

Set up your React app for CRUD operations using MongoDB Realm GraphQL — Part 2

Build React Admin Dashboard With Node js Backend