0
0
Node.jsframework~5 mins

CommonJS require and module.exports in Node.js

Choose your learning style9 modes available
Introduction
CommonJS lets you split your code into files and use them together easily. It helps organize code by sharing functions or data between files.
You want to use code from another file in your Node.js project.
You want to share a function or object with other parts of your app.
You want to keep your code clean by separating features into different files.
You are working on a Node.js app that does not use ES modules.
You want to load modules synchronously in your Node.js scripts.
Syntax
Node.js
const moduleName = require('modulePath');

module.exports = valueToExport;
Use require() to load a module or file.
Use module.exports to share what a file provides.
Examples
Load a local file named math.js from the same folder.
Node.js
const math = require('./math');
Export a function named add from a file.
Node.js
module.exports = function add(a, b) {
  return a + b;
};
Export an object with data.
Node.js
module.exports = {
  name: 'Alice',
  age: 30
};
Load a built-in Node.js module named fs.
Node.js
const fs = require('fs');
Sample Program
This example shows how to export a function from math.js and use it in app.js. The app.js file loads the add function and prints the result of adding 5 and 7.
Node.js
// math.js
function add(a, b) {
  return a + b;
}

module.exports = add;

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

console.log(add(5, 7));
OutputSuccess
Important Notes
The require function loads modules synchronously, so it pauses code until the module is ready.
You can export any value with module.exports: functions, objects, strings, numbers, etc.
File paths in require for local files need ./ or ../ to work correctly.
Summary
CommonJS uses require() to load modules and module.exports to share code.
It helps organize Node.js code by splitting it into reusable files.
Use relative paths with require for your own files, and module names for built-in or installed packages.