You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
15 Hrs
34 Min
32 Seg
Curso de Fundamentos de Node.js

Curso de Fundamentos de Node.js

Oscar Barajas Tavares

Oscar Barajas Tavares

Tipos de M贸dulos en Node.js

4/20
Resources

Modules in NodeJS are fundamental for building robust and maintainable applications. Like Lego pieces, these encapsulated code blocks with specific functionalities allow us to create complex structures from simple and reusable components. This modularity not only facilitates code maintenance, but also avoids conflicts in large-scale applications.

What are modules in NodeJS and what are their types?

Modules in NodeJS are encapsulated code blocks that fulfill a specific function. This encapsulation allows us to reuse the code in different parts of our application, facilitate its maintenance and avoid conflicts in complex projects. There are different types of modules that we can implement in our applications:

Module systems in NodeJS

In NodeJS we mainly find two module systems:

  1. CommonJS (CJS): it is the original NodeJS system, which uses:

    • Syntax: require() to import and module.exports to export .
    • File extension: .js
    • Execution: synchronous
    • It is the default system since the beginning of NodeJS.
  2. ES Modules (ESM): It is the modern system, compatible with ECMAScript 6+:

    • Syntax: import and export
    • File extension: .mjs (although .js can also be used with proper configuration)
    • Execution: asynchronous by design
    • Available on experimental basis since NodeJS version 12 and stable since version 14

Module options available

In addition to module systems, there are different types depending on their origin:

  1. Native modules: come built into NodeJS:

    • fs: for file system handling.
    • http: for creating HTTP services
    • path: for accessing file paths
    • os: to interact with the operating system
  2. Third-party modules: They are installed from NPM (Node Package Manager):

    • They are added to the project by npm install module-name
    • They extend the functionalities of our applications

How to implement modules in NodeJS?

The implementation of modules varies according to the system we use. Let's see practical examples of each one:

Implementing CommonJS

To create a module with CommonJS, we must export the functionalities we want to share:

// math.jsfunction add(a, b) { return a + b;}
function subtract(a, b) { return a - b;}
module.exports = { add, subtract };

To use this module in another file:

// main.jsconst math = require('./math');
console.log(`Sum: ${math.add(5, 3)}`);console.log(`Subtract: ${math.subtract(5, 3)}`);

When running node src/main.js, we will get:

Addition: 8Subtraction: 2

Implementing ES Modules

To create a module with ES Modules, we use the export syntax:

// math.mjsexport function multiply(a, b) { return a * b;}
export function divide(a, b) { return a / b;}

To use this module:

// main.mjsimport { multiply, divide } from './math.mjs';
console.log(`Multiplication: ${multiply(5, 3)}`);console.log(`Divide: ${divide(6, 2)}`);

When running node src/main.mjs, we will get:

Multiplication: 15Division: 3

Using native modules

Native modules are available without additional installation:

// native.jsconst fs = require('fs');
const data = fs.readFileSync('example.txt', 'utf8');console.log(`Filecontent: ${data}`);

If the file example.txt contains `Hello World`, when we run this code we will see:

File content: Hello World

Implementing third party modules

To use third-party modules, we must first install them:

npm install is-odd

Then we can use them in our code:

// third-party.jsconst isOdd = require('is-odd');
console.log(isOdd(1)); // trueconsole.log(isOdd(3)); // true

Which module system should I use?

The choice between CommonJS and ES Modules depends on several factors:

  • For new projects: it is recommended to use ES Modules (import/export), especially if you work with Node versions higher than 18.
  • For existing projects: Many projects still use CommonJS (require/module.exports), so it is important to know both systems.

The most important thing is to maintain consistency throughout the project, choosing a single module system to avoid confusion and compatibility issues.

Code modularization is a fundamental practice in NodeJS development that will allow you to build more organized, maintainable and scalable applications. I encourage you to experiment with different types of modules and find the approach that best suits your needs. Have you worked with modules in NodeJS? Share your experience and doubts in the comments section.

Contributions 4

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Ac谩 les dejo mi repositorio: <https://github.com/platzi/fundamentos-nodejs/>
Por alguna razon al colocar solo el nombre del archivo me generaba un error de que no se encontraba el archivo o directorio asi que especifique la ruta del archivo. ```js const fs = require('fs'); const data = fs.readFileSync('src/example.txt', 'utf8'); console.log(`File content: ${data}`); ```const fs = require('fs'); const data = fs.readFileSync('src/example.txt', 'utf8');console.log(`File content: ${data}`);
```js const isOdd = require('is-odd'); const color = require('colors'); console.log(isOdd('3')); console.log(isOdd('2')); //Utilizando modulo colors console.log("Hola Mundo".rainbow); console.log("Cambiando el texto de la consola".yellow) console.log(color.blue(isOdd('2'))); ``` const isOdd = require('is-odd');const color = require('colors'); console.log(isOdd('3'));console.log(isOdd('2')); //Utilizando modulo colorsconsole.log("Hola Mundo".rainbow);console.log("Cambiando el texto de la consola".yellow)console.log(color.blue(isOdd('2'))); Instale un modulo para que cuando envie un mensaje en consola este salga de un color especifico o del color del arcoiris.
Otra manera de leer el contenido de un archivo es mandando un callback, donde el primer parametro es un err y el segundo es la data del archivo ```js const fs = require('fs'); const path = require('path'); const filePath = path.join(__dirname, 'hello.txt'); fs.readFile(filePath, 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); } else { console.log(data); } }); ```const fs = require('fs');const path = require('path'); const filePath = path.join(\_\_dirname, 'hello.txt'); fs.readFile(filePath, 'utf8', (err, data) => {聽 if (err) {聽 聽 console.error('Error reading file:', err);聽 } else {聽 聽 console.log(data);聽 }});