Modules in Node.js | Lecture 4

 

Here are notes on Modules in Node.js:


Modules in Node.js

What are Modules?

  • Modules are reusable blocks of code that help organize functionality into separate files and libraries.
  • Node.js uses CommonJS modules by default.

Types of Modules in Node.js:

  1. Built-in Modules:
    • Pre-installed modules in Node.js.
    • Examples: http, fs, path, os, events.
  2. User-defined Modules:
    • Custom modules created by developers to structure application code.
  3. Third-party Modules:
    • External libraries installed via npm.
    • Example: express, lodash.

Using Modules in Node.js:

  1. Importing a Module:
    • Use the require() function to load a module.
    • Syntax:

o   const moduleName = require('module-name');

  1. Exporting from a Module:
    • Use module.exports or exports to expose functionality.
    • Syntax:

o   // In a module file (example: math.js)

o   module.exports = {

o       add: (a, b) => a + b,

o       subtract: (a, b) => a - b,

o   };

  1. Using the Exported Module:
    • Import and use the exported functions or objects.

o   // In another file (example: app.js)

o   const math = require('./math'); // './' indicates a relative path

o   console.log(math.add(2, 3)); // Outputs: 5


Built-in Modules Examples:

  1. fs (File System Module):
    • Handles file operations.

o   const fs = require('fs');

o   fs.writeFileSync('example.txt', 'Hello, Node.js!');

o   console.log(fs.readFileSync('example.txt', 'utf-8'));

  1. http (HTTP Module):
    • Creates web servers.

o   const http = require('http');

o   const server = http.createServer((req, res) => {

o       res.write('Hello from the HTTP module!');

o       res.end();

o   });

o   server.listen(3000, () => console.log('Server running on port 3000'));

  1. path (Path Module):
    • Provides utilities for file and directory paths.

o   const path = require('path');

o   console.log(path.basename('/folder/example.txt')); // Outputs: example.txt

  1. os (Operating System Module):
    • Provides system-related information.

o   const os = require('os');

o   console.log(os.platform()); // Outputs: platform (e.g., 'linux', 'win32')


Creating and Using a Custom Module:

  1. Create a Module:
    • File: greet.js

o   function sayHello(name) {

o       return `Hello, ${name}!`;

o   }

o   module.exports = sayHello;

  1. Use the Module:
    • File: app.js

o   const greet = require('./greet');

o   console.log(greet('John')); // Outputs: Hello, John!


Third-party Modules Example:

  • Install and use the lodash library:

·        npm install lodash

·        const _ = require('lodash');

·        const arr = [1, 2, 3, 4, 5];

·        console.log(_.shuffle(arr)); // Outputs: shuffled array


Advantages of Using Modules:

  1. Promotes code reusability.
  2. Improves maintainability and organization.
  3. Encourages modular design.

Let me know if you'd like more examples or in-depth explanations!

 

Comments

Popular posts from this blog

Introduction to Node.js | Lecture 1

Introduction to NPM | Lecture 2