
Modules in NodeJs
In Node.js, modules are the building blocks of your application โ they help you organize your code into reusable chunks.
๐ฆ What is a Module in Node.js?
A module is simply a file in Node.js.
Every
.js
file is its own module.Modules can export functionality (functions, variables, objects).
Other files can import that functionality using
require()
orimport
.
๐งฑ 3 Types of Modules
Type | Example |
---|---|
Core Modules | fs , http , path , url |
Local Modules | Your own files (./logger.js ) |
Third-party | Installed via npm (express , etc.) |
โ Local Module Example
1. math.js
โ your own module
const math = require('./math');console.log(math.add(5, 3)); // Output: 8
๐ Core Module Example
const path = require('path');const filePath = path.join(__dirname, 'test.txt');console.log(filePath);
๐งโโ๏ธ How Exporting Works
You can export a function, object, class, or anything else:
// file: greet.jsmodule.exports = function(name) { return `Hello, ${name}`;};
// file: app.jsconst greet = require('./greet');console.log(greet('Alice')); // Hello, Alice
๐งช ES6 Modules (import/export
)
If you're using "type": "module"
in package.json
, you can use ES6 syntax:
// math.jsexport function add(a, b) { return a + b;}// app.jsimport { add } from './math.js';console.log(add(2, 3));
๐ Common Core Modules
Module | Use |
---|---|
fs | File system (read/write files) |
http | Create servers |
path | File paths |
url | Parse and format URLs |
events | Event handling |
os | Get system info |