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.
- Create a file for the module.
touch format.js
- 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 };
- Create an
index.js
to import the CSJ module.
touch index.js
- Import module with destructuring.
const { toUpper } = require('./format');
console.log(toUpper('this will be uppercase'));
- Execute it.
node index.js
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.
Top comments (0)