Thuta Learning
IntermediateWeb Developmentbeginner

File System (fs)

Relax. We'll talk through this in plain words — no textbook voice.

fs is Node.js's built-in module for working with the file system. It's commonly used for backend tasks like reading files, writing files, checking folders, saving log files, and reading JSON data.

javascript
const fs = require('fs');

const note = 'Node.js can write files!';

// Write a file
fs.writeFile('note.txt', note, 'utf8', (writeErr) => {
  if (writeErr) {
    console.error('Write error:', writeErr.message);
    return;
  }

  // Read the file after writing
  fs.readFile('note.txt', 'utf8', (readErr, data) => {
    if (readErr) {
      console.error('Read error:', readErr.message);
      return;
    }

    console.log('File content:', data);
  });
});

First, we write a note.txt file. After writing, we read it back inside the callback using fs.readFile(). If there's an error, we return early and show the error message.

You should see
File content: Node.js can write files!

Info

An incorrect file path can cause read/write errors. In production apps, you should never do file operations without error handling.

Easy traps

  • If you try to read a file before the write to it has finished, you might end up with empty or stale data. In async code, be careful to control the order with callbacks, promises, or async/await.

Exercise

You can manage things like user upload logs, server activity logs, small JSON config files, and generated report files with the fs module.

You'll know it worked when:

File System (fs) | Thuta Learning