File System (fs) Module

The fs module allows you to work with the file system on your computer. You can read, write, create, update, and delete files.

1. Importing the fs Module

const fs = require('fs');
// Or using promises (recommended)
const fsPromises = require('fs/promises');

2. Reading Files

You can read files synchronously (blocking) or asynchronously (non-blocking).Always prefer asynchronous methods in production to keep the application responsive.

// Asynchronous way (using callback)
fs.readFile('hello.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

// Using Promises (Modern)
async function readFile() {
  try {
    const data = await fsPromises.readFile('hello.txt', 'utf8');
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

3. Writing Files

The writeFile method replaces the content if the file exists, or creates a new file if it doesn't.

const content = 'Learning Node.js is fun!';
fs.writeFile('notes.txt', content, (err) => {
  if (err) throw err;
  console.log('File written successfully!');
});

4. Appending to Files

If you want to add content to an existing file instead of replacing it, use appendFile.

fs.appendFile('notes.txt', '\nNew line added!', (err) => {
  if (err) throw err;
  console.log('Content appended!');
});

5. Deleting Files

fs.unlink('temp.txt', (err) => {
  if (err) throw err;
  console.log('File deleted!');
});
Best Practice: Always handle errors in file operations. A missing file or bad permissions can crash your application if not caught properly.