Course contentsShow
← JavaScript
Lesson 1440 of 2,72331. ModulesFree lesson

Require: Importing Another Module

Use require() to load and execute another file, receiving its exported value.

Require: Importing Another Module

You'll learn how to bring another file's exported code into your current file using require().

What require() Does

In CommonJS (Node.js's traditional module system), require() is the function you use to load and execute another JavaScript file. When you call require() with a file path, Node.js:

  1. Finds the file
  2. Executes all its code
  3. Returns whatever that file exported via module.exports

Think of require() like ordering a specific item from a restaurant kitchen. You tell the kitchen what you want (the file path), they prepare it (execute the code), and hand you the finished dish (the exported value).

Basic Syntax

// math.js
module.exports = {
  add: (a, b) => a + b,
  multiply: (a, b) => a * b
};

// app.js
const math = require('./math.js');

console.log(math.add(5, 3));      // 8
console.log(math.multiply(4, 2)); // 8

The require() function receives the exported object and assigns it to the math variable. Now you can use everything that was exported.

Relative Paths

When requiring your own files, use relative paths starting with ./ (same directory) or ../ (parent directory):

const utils = require('./utils.js');
const helpers = require('../helpers.js');

For built-in or installed packages, just use the name:

const fs = require('fs');

Key Takeaway: require() loads another file, executes its code, and returns the value assigned to module.exports, letting you use code from other files in your application.