Modules
JavaScript Modules and [Link] fs
Module — Complete Notes
1. What Are Modules in JavaScript?
A module is a reusable block of code that encapsulates logic, variables,
functions, or classes into separate files.
Instead of writing everything in one huge file, modules allow developers to split
applications into smaller, manageable, and reusable parts.
Why Modules Exist
Without modules:
Code becomes difficult to maintain
Variable naming conflicts occur
Reusability becomes poor
Large applications become messy
Team collaboration becomes difficult
Modules solve these problems by introducing:
Encapsulation
Reusability
Separation of concerns
Better maintainability
Better scalability
Real-World Example
Imagine an e-commerce application.
Modules 1
Instead of:
// everything in one file
We split it into:
[Link]
[Link]
[Link]
[Link]
[Link]
Each file becomes a module.
2. Types of Modules in JavaScript
There are mainly two module systems in JavaScript:
Module System Used In
CommonJS (CJS) [Link] (traditional)
ES Modules (ESM) Modern JavaScript
3. CommonJS Modules (CJS)
CommonJS is the older [Link] module system.
It uses:
require()
[Link]
Exporting in CommonJS
[Link]
function add(a, b) {
return a + b;
Modules 2
}
[Link] = add;
Importing in CommonJS
[Link]
const add = require("./math");
[Link](add(2, 3));
Output:
Exporting Multiple Things
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
[Link] = {
add,
subtract,
};
Import:
Modules 3
const math = require("./math");
[Link]([Link](5, 2));
4. ES Modules (ESM)
Modern JavaScript uses ES Modules.
It uses:
import
export
Enabling ES Modules in [Link]
Add this to [Link] :
{
"type": "module"
}
Exporting in ESM
[Link]
export function add(a, b) {
return a + b;
}
Importing in ESM
[Link]
Modules 4
import { add } from "./[Link]";
[Link](add(2, 3));
Default Export
export default function greet() {
[Link]("Hello");
}
Import:
import greet from "./[Link]";
5. Difference Between CommonJS and ES
Modules
Feature CommonJS ES Modules
Import require() import
Export [Link] export
Loading Synchronous Asynchronous
Used In Traditional [Link] Modern JS
Tree Shaking No Yes
Static Analysis Poor Better
6. Types of Modules in [Link]
[Link] mainly has three types of modules.
1. Core Modules
Built into [Link].
Modules 5
Examples:
fs
path
http
os
events
crypto
Usage:
const fs = require("node:fs");
2. Local Modules
Modules created by developers.
Example:
[Link]
Usage:
const utils = require("./utils");
3. Third-Party Modules
Installed using npm.
Example:
npm install express
Usage:
const express = require("express");
Modules 6
7. Module Resolution in [Link]
When Node sees:
require("fs")
It checks:
1. Core module
2. node_modules
3. Local files
Relative Paths
Syntax Meaning
./ Current directory
../ Parent directory
/ Root directory
8. What Is the fs Module?
The fs module stands for:
File System
It is a built-in [Link] module used for:
Creating files
Reading files
Updating files
Deleting files
Creating folders
Manipulating directories
Modules 7
Importing fs
const fs = require("node:fs");
Or promise-based:
const fs = require("node:fs/promises");
9. Synchronous vs Asynchronous
Methods
Type Blocking?
Sync Yes
Async No
Synchronous Example
const data = [Link]("[Link]", "utf-8");
[Link](data);
Execution waits until file reading completes.
Asynchronous Example
[Link]("[Link]", "utf-8", (error, data) => {
if (error) {
[Link](error);
return;
}
[Link](data);
});
Modules 8
Execution continues without blocking.
Interview Important Point
[Link] is single-threaded.
Blocking operations reduce performance.
Therefore:
Prefer async operations in production
Sync methods are mostly used for scripts/tools
10. Creating Files
writeFileSync()
const fs = require("node:fs");
[Link]("[Link]", "Hello World", "utf-8");
If file does not exist:
It creates the file
If file exists:
It overwrites the file
Async Version
[Link]("[Link]", "Hello World", (error) => {
if (error) {
[Link](error);
return;
}
Modules 9
[Link]("File created");
});
11. Reading Files
readFileSync()
const data = [Link]("[Link]", "utf-8");
[Link](data);
Async Version
[Link]("[Link]", "utf-8", (error, data) => {
if (error) {
[Link](error);
return;
}
[Link](data);
});
12. Appending Data
Adds data without deleting existing content.
[Link]("[Link]", "\nNew line added");
Async Version
Modules 10
[Link]("[Link]", "\nAnother line", (error) => {
if (error) {
[Link](error);
return;
}
[Link]("Data appended");
});
13. Deleting Files
unlinkSync()
[Link]("[Link]");
Async Version
[Link]("[Link]", (error) => {
if (error) {
[Link](error);
return;
}
[Link]("File deleted");
});
14. Creating Directories
mkdirSync()
Modules 11
[Link]("Projects");
Creating Nested Directories
[Link]("Projects/React/Auth", {
recursive: true,
});
Async Version
[Link]("Projects", (error) => {
if (error) {
[Link](error);
return;
}
[Link]("Folder created");
});
15. Removing Directories
[Link]("Projects");
Modern approach:
[Link]("Projects", {
recursive: true,
force: true,
});
16. Checking File Existence
Modules 12
if ([Link]("[Link]")) {
[Link]("File exists");
}
17. Renaming Files
[Link]("[Link]", "[Link]");
18. File Information Using statSync()
const stats = [Link]("[Link]");
[Link](stats);
Useful methods:
[Link]()
[Link]()
19. Working with Paths
Always prefer using [Link]() .
const path = require("node:path");
const filePath = [Link](
"Projects",
"React",
"[Link]"
);
Better cross-platform compatibility.
Modules 13
20. Promise-Based fs
Modern [Link] applications often use:
const fs = require("node:fs/promises");
Example:
const fs = require("node:fs/promises");
async function readData() {
try {
const data = await [Link]("[Link]", "utf-8");
[Link](data);
} catch (error) {
[Link](error);
}
}
readData();
21. Common Errors in fs
MODULE_NOT_FOUND
Occurs when module path is incorrect.
ENOENT
Means:
No such file or directory
Example:
Modules 14
[Link]("[Link]");
EACCES
Permission denied.
22. Interview Questions
Q1. What are modules in JavaScript?
Modules are reusable files containing related code that help organize
applications into smaller maintainable units.
Q2. Difference between CommonJS and
ES Modules?
CommonJS ES Modules
require() import
[Link] export
Synchronous Asynchronous
Traditional [Link] Modern JavaScript
Q3. What is the purpose of the fs
module?
The fs module allows interaction with the filesystem including:
creating files
reading files
updating files
deleting files
Modules 15
directory operations
Q4. Difference between sync and async
file operations?
Sync Async
Blocking Non-blocking
Slower scalability Better performance
Simpler Preferred in servers
Q5. Why is async preferred in [Link]?
Because [Link] is single-threaded.
Blocking operations freeze the event loop and reduce scalability.
Q6. What does recursive: true do in
mkdir?
It creates nested folders automatically.
Example:
[Link]("A/B/C", {
recursive: true,
});
Q7. Difference between writeFile and
appendFile ?
writeFile appendFile
Replaces content Adds content
Modules 16
Q8. Why use node:fs instead of fs ?
node:fs explicitly indicates that the module is a built-in [Link] core module.
Q9. What is module encapsulation?
Variables/functions inside a module remain private unless exported.
Q10. What is a dependency?
A package/module required by another package to function.
23. Best Practices
Prefer async methods in backend applications
Use node: prefix for core modules
Use [Link]() for paths
Handle errors properly
Avoid blocking the event loop
Use promises/async-await in modern apps
24. Mini Practical Example
const fs = require("node:fs");
const path = require("node:path");
const folderPath = [Link]("Stories", "Space");
const filePath = [Link](folderPath, "[Link]");
[Link](folderPath, {
recursive: true,
});
[Link](
Modules 17
filePath,
"Space exploration is fascinating.",
"utf-8"
);
const data = [Link](filePath, "utf-8");
[Link](data);
[Link](filePath, "\nNew chapter added.");
[Link](filePath, [Link](folderPath, "updated-stor
[Link]"));
25. Key Takeaways
Modules help organize and reuse code
CommonJS and ES Modules are the two major systems
fs is [Link]' filesystem module
Async operations are preferred in production
[Link]() improves portability
[Link] manages dependencies
[Link] locks dependency versions
[Link] core modules can use node: prefix
Modules 18