Node.js β€’ File System Module

Node.js File System (fs)

A student-friendly guide to reading, writing, appending, opening, closing and deleting files using Node.js.

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.

πŸ“ Files & directoriesCreate, read, update and remove file-system content.
βš™οΈ Two approachesSupports both synchronous and asynchronous methods.
πŸ›‘οΈ Error handlingHelps handle problems such as missing files and permission errors.
πŸ”Œ Built inNo separate package is required.

Import fs

const fs = require("fs");
ELI10: Think of 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.

Start→Read file→Wait→Continue
  • 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.

Start→Start file operation→Continue other work→Handle result
  • 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)
ParameterSimple meaning
pathFile name or complete file path.
flagsDefines how the file is opened, such as r, w, a, r+.
modeFile access permissions.
callbackRuns 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)
ParameterMeaning
fdFile descriptor returned by fs.open().
bufferMemory area where the data is stored.
offsetWhere writing into the buffer should begin.
lengthNumber of bytes to read.
positionStarting position in the file; null uses the current file position.
callbackRuns 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

Remember: 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.

MethodStylePurpose
fs.appendFile()AsynchronousAdd data and continue without blocking.
fs.appendFileSync()SynchronousAdd 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.

Important: 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

OperationNode.js methodEasy meaning
Importrequire("fs")Get the file-system toolbox.
Read synchronouslyfs.readFileSync()Read and wait.
Read asynchronouslyfs.readFile()Read and continue.
Openfs.open()Open a file and get its descriptor.
Read opened filefs.read()Read using the descriptor and buffer.
Writefs.writeFile()Write/replace file content.
Appendfs.appendFile()Add data at the end.
Append synchronouslyfs.appendFileSync()Add data and wait.
Closefs.close()Close the file descriptor.
Delete filefs.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().