You come across modules or something in most programming languages. So is the case for JavaScript and also with NodeJS. In this post, we will learn about NodeJS Modules.

This will include creating your own module or using a third-party module.

In case you are new to NodeJS, check out this post on beginning with NodeJS.

1 – What are NodeJS Modules?

A typical NodeJS application is made up of many JavaScript files.

Within the context of your application, each of these files has a specific reason to exist. While you could potentially create a giant file containing all the functionality of an application, such an approach is not good for the future health of your application.

For your application to stay organized and efficient, you should split its functionalities into separate files. In fact, you would also want to organize parts of your application into folders for an even better management.

Each of these JavaScript files or folders containing a code library is a NodeJS module.

2 – NodeJS Exports and Require Keywords

When you divide your NodeJS application into several modules, it is natural that these files need to access content from one another whenever necessary.

To facilitate this requirement of content access between modules or files, NodeJS provides two special keywords:

  • The exports keyword exposes some properties (variables or functions) from a JavaScript file or module.
  • The require keyword helps load libraries of code and module from other modules or packages.

Let us see the two keywords in action.

As an example, we create a file or module named messages.js. This module contains a list of greeting messages. We expose this list using the exports keyword as below.

exports.messages = ['hi', 'welcome to nodejs demo', 'are you enjoying it?'

The exports object is a property of the module object.

Yes, module is both the name of the individual JavaScript files and one of its global objects. exports is nothing but a shorthand for module.exports.

The exports keyword can also export functions. Check out the code below from a file named addNumbers.js.

exports.add = (num1, num2) => num1 + num2;

Here, the function add accepts two numbers and returns their sum. We are exporting the function from this particular module.

We can now use these exported functions in another module. Refer to the below code.

const messageModule = require('./messages');
const addNumberModule = require('./addNumbers.js');

messageModule.messages.map(message => {
    console.log(message);
})

console.log(addNumberModule.add(5, 10));

Using the properties of another module is matter of requiring them using the require keyword.

Just like exports, require is another NodeJS global object. Its job is to locally introduce methods and objects from other modules.

For example, the statement require('./messages') looks for a module known as messages.js within the project directory and allows our current module to use any properties available on the exports object in messages.js.

Both exports and require come from CommonJS. Basically, CommonJS is a tool that helps JavaScript run outside a browser by helping define how modules are used. NodeJS leverages CommonJS.

3 – Using Third-Party NodeJS Modules

While we certainly create many modules within our application, we also end up using a lot of third-party modules.

Applications can grow pretty big in scope and it is not possible to build everything from scratch. In fact, such an endeavour is counter-productive. Most of the time, someone has already built a functionality that you want in your application. In such cases, it is better to utilize these third-party modules.

3.1 – Using NPM or Node Package Manager.

In the NodeJS ecosystem, we have npm (a package manager) where we can find modules and packages built by other developers.

Some of the common command we can use to interact with npm are listed below:

  • npm init – This command initializes a NodeJS application. Basically, it creates a package.json file with a bunch of metadata about our application.
  • npm install – This command installs a NodeJS package globally or specific to our project.
  • npm publish – This command saves and uploads a package we built to the npm package community.
  • npm start – This command runs our NodeJS application. Of course, before using it, we need to configure it property within the package.json file.
  • npm stop – This command quits the running application
  • npm docs – This command opens the documentation web page for a particular package.

The most common command we end us using is npm install <package>.

By default, this command installs a package as a dependency for our specific application. However, if we append the flag --global, the package is installed globally on our computer. We install packages globally where we want to utilize a package in our development machine (example, nodemon and create-react-app).

3.2 – NodeJS Modules, Packages and Dependencies

At this point, you might get confused between various terms such as modules, packages and dependencies in the context of a NodeJS application.

  • Modules are individual JavaScript files. These files usually contain code related to a single concept, functionality or library.
  • Packages contain multiple modules or a single module. They are used to group JavaScript files into a bigger piece of functionality.
  • Dependencies are NodeJS modules used by an application or another module. A package is also an application dependency and must be installed before the application is expected to run.

3.3 – NodeJS Third-Party Module or Package Demo

Having developed a good understanding of NodeJS modules and third-party package, we will now learn how to use one in our application.

  • As a first step, we execute the command npm init to initialize our project. This command needs to be run in the root of our project directory. It will prompt for answering a few questions such as the name of the project, version, description, author and so on. You can enter values for these questions and use the default values. Once the command runs, you’ll find the package.json file within your project directory.
{
  "name": "nodejs-module",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \\"Error: no test specified\\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
  • Next, we need to install a third-party package. For our demo, we will use a nice package that provides information about countries, states and cities. To install this package, we execute the command npm install country-state-city. Below is our package.json file after the installation. There is a section that keeps track of the dependencies. Also, at this point, you will find a new folder node_modules within your project directory. Basically, this is where the external module has been installed in order to make it available to use.
{
  "name": "nodejs-module",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \\"Error: no test specified\\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "country-state-city": "^3.1.2"
  }
}
  • Finally, we can use the package within our application. First of all, we use require to make the module country-state-city available within our JavaScript file. Next, we can use it to call the exported function getCountryByCode().
const Country = require('country-state-city').Country;
let country = Country.getCountryByCode('FR');
console.log(country)
  • On running the program using node index.js, you should see similar output printed in the console.
{
  name: 'France',
  isoCode: 'FR',
  flag: '??',
  phonecode: '33',
  currency: 'EUR',
  latitude: '46.00000000',
  longitude: '2.00000000',
  timezones: [
    {
      zoneName: 'Europe/Paris',
      gmtOffset: 3600,
      gmtOffsetName: 'UTC+01:00',
      abbreviation: 'CET',
      tzName: 'Central European Time'
    }
  ]
}

Conclusion

In this post, we learnt about NodeJS modules and how you can create your own modules for managing the various functionalities.

We also utilized npm to leverage the power of external packages while building our application. In the process, we learnt about exports and require keywords along with steps to manage dependencies in our application.

Basically, whatever we have learnt in this post forms the foundation of building more complex application using NodeJS.

Categories: BlogNodeJS

Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *