Node.js Custom Modules

A custom module is a JavaScript file created by the programmer and reused in another Node.js file.

Example

math.js

function add(a, b) {
    return a + b;
}

module.exports = add;
        

app.js

const add = require("./math");

console.log(add(10, 20));
        
Output:

30

Explanation

  1. Create a separate JavaScript file.
  2. Write a function inside the file.
  3. Export it using module.exports.
  4. Import it using require().
  5. Use the function in another file.
← Back to Home