Node Modules

Node.js Modules: Introduction to CommonJS

In Node.js, a Module is essentially a JavaScript file containing code that is designed to perform a specific task. Think of modules as JavaScript libraries. By breaking your code into separate modules, you make your applications easier to manage, debug, and scale.

Node.js uses a module system called CommonJS by default. In this tutorial, you will learn how to use built-in modules, create your own local modules, and properly include them in your projects.


1. What are Built-in Core Modules?

Node.js comes with a set of built-in modules that you can use without having to install anything extra. These modules provide essential functionality like reading files, building web servers, and working with file paths.

To include a built-in module in your file, you use the require() function.

Example: Using the fs (File System) Module

app.js

// Require the built-in 'fs' module
const fs = require('fs');

// Use it to write text to a file fs.writeFileSync('message.txt', 'Hello, Node.js Modules!');

console.log('File written successfully.');

Other highly popular core modules include:


2. Creating Your Own Local Modules

As your application grows, you shouldn't put all your code in a single app.js file. Instead, you can create custom modules and export functions or variables to be used in other files.

Let's create a custom module that handles basic math operations.

  1. Create a file named mathUtils.js.
  2. Write some functions.
  3. Use module.exports to make them available outside the file.

mathUtils.js

const add = (a, b) => {
  return a + b;
};

const subtract = (a, b) => { return a - b; };

// Export the functions as an object module.exports = { add, subtract };


3. Importing Your Local Modules

Now that we have exported our custom functions from mathUtils.js, we can import them into our main file using the require() function.

When requiring a local module, you must provide the relative path to the file (e.g., ./ for the same directory).

app.js

// Require the local module
// Notice the './' which tells Node it's a local file, not a core module
const math = require('./mathUtils');

let sum = math.add(10, 5); let difference = math.subtract(10, 5);

console.log("Sum:", sum); console.log("Difference:", difference);

Pro Tip: You don't need to add the .js extension when requiring local JavaScript files. Node.js automatically assumes a .js extension if none is provided.


4. Exporting a Single Item

Sometimes, your module only needs to export one single function or class, rather than an entire object of functions. You can assign it directly to module.exports.

greet.js

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

// Exporting just the function directly module.exports = sayHello;

And then in your main file:

app.js

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

console.log(greet("Alice")); // Output: Hello, Alice!


Exercise

?

Which keyword is used in CommonJS to import a module into another file?