Node.js – File System Module (fs)
Subject: nodejs
Node.js – File System Module (fs)
The File System (fs) module in Node.js allows you to interact with the file system on your computer. With fs
, you can read, write, delete, update, rename, and stream files and directories using both synchronous and asynchronous methods.
Why Use the fs Module?
- Automate file and directory management.
- Build backend features like loggers, upload/download systems, and configuration loaders.
- Efficiently handle large files using streams.
- Work with both callback-based and promise-based APIs.
Importing the fs Module
You can also use the promise-based API:
1. Reading Files
Asynchronous Method:
Synchronous Method:
2. Writing Files
Asynchronous:
Synchronous:
writeFile()
will overwrite the file if it exists.
3. Appending Data to a File
4. Renaming Files
5. Deleting Files
6. Creating a Directory
7. Reading Contents of a Directory
8. File Stats and Metadata
9. Using Streams (for Large Files)
Reading a file with stream:
Writing to a file with stream:
10. Using fs.promises for Modern Async/Await
Key Takeaways
- The
fs
module is used to perform file and directory operations. - Provides both synchronous and asynchronous (non-blocking) methods.
- Use streams for large file operations.
- Use
fs.promises
withasync/await
for cleaner, modern code. - Always handle errors in file operations to avoid crashes.