File System Module in Node.js
⏱ Estimated reading time: 2 min
The File System (fs) module allows Node.js to interact with files and directories on the system.
It is a core module, so no installation is required.
1. Types of File System Operations
The fs module supports three styles of operations:
1.1 Synchronous (Blocking)
-
Executes operations sequentially
-
Blocks the event loop
-
Suitable for scripts and startup tasks
Example:
1.2 Asynchronous (Callback-based)
-
Non-blocking
-
Uses callbacks
-
Preferred for production apps
Example:
1.3 Promise-based (fs/promises)
-
Uses Promises and
async/await -
Clean and modern approach
Example:
2. Common File Operations
2.1 Reading Files
2.2 Writing Files
2.3 Appending Files
2.4 Deleting Files
3. Directory Operations
3.1 Create Directory
3.2 Read Directory
3.3 Remove Directory
4. File Information (Stats)
5. File Streams
Streams allow reading/writing large files efficiently.
5.1 Read Stream
5.2 Write Stream
6. File Permissions
7. Watching Files
8. Error Handling
Always handle errors properly:
9. When to Use Which Method
| Use Case | Recommended |
|---|---|
| Server apps | Async / Promises |
| Startup scripts | Sync |
| Large files | Streams |
10. Advantages of fs Module
-
Built-in and fast
-
Supports sync & async
-
Handles files and directories
-
Stream support for large data
11. Summary
-
fsis a core Node.js module -
Supports synchronous, asynchronous, and promise-based APIs
-
Used for file and directory operations
-
Streams improve performance for large files
Register Now
Share this Post
← Back to Tutorials