Use modules to write reusable code in Node.js
Posted
Updated
Europe’s developer-focused job platform
Let companies apply to you
Developer-focused, salary and tech stack upfront.
Just one profile, no job applications!
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).
💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times.
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.
touch format.js
'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 };
index.js
to import the CSJ module.touch index.js
const { toUpper } = require('./format');
console.log(toUpper('this will be uppercase'));
node index.js
The output to the terminal should be THIS WILL BE UPPERCASE
.
require
function will only return what is exported from the module.require
function.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.
Never miss an article.