DEV Community

Mario
Mario

Posted on • Originally published at mariokandut.com on

How to create a CJS module

This article is based on Node v16.14.0.

Modules are building blocks of code structures and allow Node.js developers to build better structure, reuse, and distribute code. Since Node v14 , there are two kinds of modules, CommonJS Modules (CJS) and EcmaScript Modules (ESM). This article is about CommonJS modules (CJS).

When importing a CJS module, you have to require it. The result of require is in some cases a function, which creates a new instance, but this is not guaranteed. The require function will always return what is exported from the module.

Let's create a local module, which will convert any input string to uppercase and use it in five steps.

  1. Create a file for the module.
touch format.js
Enter fullscreen mode Exit fullscreen mode
  1. Create a simple function which converts any input string to uppercase.
'use strict'
const toUpper = str => {
  if (typeof str === 'symbol') str = str.toString(); // convert to string if symbol is used as input
  str += '';
  return str.toUpperCase();
};

module.exports = { toUpper };
Enter fullscreen mode Exit fullscreen mode
  1. Create an index.js to import the CSJ module.
touch index.js
Enter fullscreen mode Exit fullscreen mode
  1. Import module with destructuring.
const { toUpper } = require('./format');
console.log(toUpper('this will be uppercase'));
Enter fullscreen mode Exit fullscreen mode
  1. Execute it.
node index.js
Enter fullscreen mode Exit fullscreen mode

The output to the terminal should be THIS WILL BE UPPERCASE.

TL;DR

  • The require function will only return what is exported from the module.
  • CommonJS modules are imported with the require function.
  • Modularization helps to abstract complexity.

Thanks for reading and if you have any questions , use the comment function or send me a message @mariokandut.

If you want to know more about Node, have a look at these Node Tutorials.

References (and Big thanks):

JSNAD,CommonJS

Top comments (0)