Node modules

Node modules are reusable pieces of code in Node.js, a popular JavaScript runtime environment. They can be used to include various functionalities, like file handling, networking, or database interaction, in your Node.js application. Node modules come in two forms:

1. Core Modules:

  • Built into Node.js and can be used without installing anything.
  • Examples include:
    • fs - used to handle file systems.
    • http or https - for creating HTTP(S) servers
    • events - used to handle events.
    • util - used to handle utility functions e.g deprecate, inspect and format.
    • buffer - used to handle binary data.
    • stream - used to handle streaming data.
    • path - provides utilities for working with file and directory paths. To check out the list of all the other Node.js core modules, check out the official documentation here.

2. External Modules (or Packages):

  • Created by the Node.js community and can be installed via npm (Node Package Manager).
  • Examples include:
    • express for building web applications.
    • mongoose for interacting with MongoDB databases.
    • lodash for utility functions.

In Node.js, the require function is used to import modules, JSON files, and other resources into your JavaScript code. It allows you to access functionality defined in other files, which helps organize and modularize your code. Here's a breakdown of how require works:

Basic Usage

  1. Loading Built-in Modules: Node.js has several built-in modules (like fs, http, etc.) that you can load directly:

    const fs = require('fs'); // File system module
    const http = require('http'); // HTTP module

  2. Loading Local Modules: You can also load your own modules (files in your project):

    const myModule = require('./myModule'); // Loads a module from a local file
  3. Loading Third-Party Modules: If you have installed a package using npm (like express), you can require it as well:
    const express = require('express'); // Loads the Express framework

Example : Here’s a simple example that demonstrates using require:

myModule.js

function sayHello(name) {
  return `Hello, ${name}!`;
}

module.exports = sayHello; // Export the function

app.js

const sayHello = require('./myModule'); // Import the module
console.log(sayHello('World')); // Outputs: Hello, World!

Key Points

  • CommonJS Module System: require is part of the CommonJS module system, which is used by Node.js for module management.
  • Caching: When a module is required, it is cached. Subsequent calls to require the same module return the cached version.
  • Relative vs. Absolute Paths: Use ./ for local files and a package name for installed packages. For absolute paths, you might need to use Node's path module or other utilities.

Conclusion

The require function is fundamental in Node.js for including modules and organizing code effectively. It helps create modular applications by breaking down functionalities into separate files.