1. What is the File System module?
The fs (File System) module is a built-in Node.js API used to perform file and directory operations on the server.
Import fs
const fs = require("fs");
fs as Node.js's toolbox for working with files and folders.2. Synchronous approach
A synchronous, or blocking, operation waits for one task to finish before moving to the next task.
- Follows a step-by-step execution flow.
- Pauses program flow while the operation runs.
- Prevents other work from progressing through that flow.
- Subsequent tasks start only after completion.
- Long-running operations may affect responsiveness.
βοΈ Easy way to remember
Synchronous = βWait for me.β
The program waits until the file operation finishes.
Example: readFileSync()
const fs = require("fs"); // Synchronous read const data = fs.readFileSync('input.txt'); console.log("Synchronous read: " + data.toString());
Output: Synchronous read: Geeks: A computer science portal
Use cases: lightweight tasks that finish quickly and situations where simplicity is more important than avoiding blocking.
3. Asynchronous approach
An asynchronous, or non-blocking, operation starts a task without waiting for it to finish. The program can continue and handle the result later.
- Execution continues without waiting for completion.
- The operation works in the background from the application's point of view.
- The result is handled when it is ready.
- Useful for performance and responsiveness.
βοΈ Easy way to remember
Asynchronous = βYou do that; I'll continue.β
Example: readFile()
const fs = require("fs"); // Asynchronous read fs.readFile("input.txt", function (err, data) { if (err) { return console.error(err); } console.log("Asynchronous read: " + data.toString()); });
Output: Asynchronous read: Geeks: A computer science portal
Use cases: heavy or time-consuming tasks and applications where responsiveness matters.
4. Opening a file
fs.open() opens a file and returns a file descriptor, which can be used for further file operations.
fs.open(path, flags, mode, callback)
| Parameter | Simple meaning |
|---|---|
| path | File name or complete file path. |
| flags | Defines how the file is opened, such as r, w, a, r+. |
| mode | File access permissions. |
| callback | Runs after the operation and receives the error and file descriptor. |
const fs = require("fs"); console.log("opening file!"); fs.open("input.txt", "r+", function (err, fd) { if (err) return console.error(err); console.log("File open successfully"); });
Output: opening file! β File open successfully
5. Reading a file
fs.read() reads data from an already-open file into memory using its file descriptor.
fs.read(fd, buffer, offset, length, position, callback)
| Parameter | Meaning |
|---|---|
| fd | File descriptor returned by fs.open(). |
| buffer | Memory area where the data is stored. |
| offset | Where writing into the buffer should begin. |
| length | Number of bytes to read. |
| position | Starting position in the file; null uses the current file position. |
| callback | Runs after reading and receives the error and read result. |
Example
const fs = require("fs"); const buf = Buffer.alloc(1024); console.log("opening an existing file"); fs.open("input.txt", "r+", function (err, fd) { if (err) return console.error(err); console.log("File opened successfully!"); console.log("reading the file"); fs.read(fd, buf, 0, buf.length, 0, function (err, bytes) { if (err) console.log(err); console.log(bytes + " bytes read"); if (bytes > 0) { console.log(buf.slice(0, bytes).toString()); } }); });
Output: opening an existing file β File opened successfully! β reading the file β 40 bytes read β Geeks: A computer science portal
6. Writing to a file
fs.writeFile() asynchronously writes data to a file. If the file already exists, the operation overwrites its existing content.
fs.writeFile(path, data, options, callback)
- path: file location or file descriptor.
- data: content to write, such as a string or buffer.
- options: controls encoding, mode and flag.
- callback: runs when writing completes.
const fs = require("fs"); console.log("writing into existing file"); fs.writeFile("input.txt", "Geeks", function (err) { if (err) return console.error(err); console.log("Data written successfully!"); console.log("Let's read newly written data"); fs.readFile("input.txt", function (err, data) { if (err) return console.error(err); console.log("Asynchronous read: " + data.toString()); }); });
Output: writing into existing file β Data written successfully! β Let's read newly written data β Asynchronous read: Geeks
writeFile() replaces the existing content. If you want to keep existing content and add more, use appendFile().7. Appending to a file
Appending means adding new data to the end of an existing file without overwriting its current content.
| Method | Style | Purpose |
|---|---|---|
fs.appendFile() | Asynchronous | Add data and continue without blocking. |
fs.appendFileSync() | Synchronous | Add data and wait for completion. |
Asynchronous example
const fs = require("fs"); let data = "\nLearn Node.js"; fs.appendFile("input.txt", data, "utf8", function (err) { if (err) throw err; console.log("Data is appended to file successfully."); });
Synchronous example
const fs = require("fs"); const data = "\nLearn Node.js"; fs.appendFileSync("input.txt", data, "utf8"); console.log("Data is appended to file successfully.");
βοΈ Before β After
Before: Geeks: A computer science portal
After: Geeks: A computer science portal
Learn Node.js
8. Closing a file
fs.close() asynchronously closes an open file descriptor and releases the associated system resources.
fs.close(fd, callback)
- fd: integer representing the file descriptor.
- callback: runs after closing completes.
- err: indicates a failure, if one occurs.
- Do not close a descriptor while an active file operation is using it.
// Close the opened file. fs.close(fd, function (err) { if (err) { console.log(err); } console.log("File closed successfully."); });
Output: File closed successfully.
9. Deleting a file
fs.unlink() deletes a file or symbolic link from the file system.
fs.unlink() is for files or symbolic links, not directories. The source material notes that fs.rm() is used to delete directories.fs.unlink(path, callback)
const fs = require("fs"); console.log("deleting an existing file"); fs.unlink("input.txt", function (err) { if (err) return console.error(err); console.log("File deleted successfully!"); });
Output: deleting an existing file β File deleted successfully!
10. Quick revision
| Operation | Node.js method | Easy meaning |
|---|---|---|
| Import | require("fs") | Get the file-system toolbox. |
| Read synchronously | fs.readFileSync() | Read and wait. |
| Read asynchronously | fs.readFile() | Read and continue. |
| Open | fs.open() | Open a file and get its descriptor. |
| Read opened file | fs.read() | Read using the descriptor and buffer. |
| Write | fs.writeFile() | Write/replace file content. |
| Append | fs.appendFile() | Add data at the end. |
| Append synchronously | fs.appendFileSync() | Add data and wait. |
| Close | fs.close() | Close the file descriptor. |
| Delete file | fs.unlink() | Remove a file. |
π§ One-line memory map
OPEN β READ / WRITE β APPEND β CLOSE β DELETE
And remember: Sync = wait β’ Async = continue
Self-check
1. What does the fs module do?
It provides Node.js file and directory operations such as reading, writing, appending, opening, closing and deleting.
2. What is the main idea of synchronous file operations?
The program waits for the current operation to finish before moving on.
3. What is the main idea of asynchronous file operations?
The program can continue while the file operation completes and its result is handled later.
4. Which method appends without overwriting?
fs.appendFile() or fs.appendFileSync().
5. Which method deletes a file?
fs.unlink().