Implement Node.js File Class with read(), write(), delete()

Creating a robust file handling class in Node.js is essential for dealing with the file system efficiently. Here, we will discuss a Node.js File class that encompasses methods readFile(), writeFile(), and deleteFile() that are based on asynchronous operations leveraging the async/await syntax. Understanding these methods will allow for seamless file manipulation within your Node.js applications.

Node.js File Class

Node.js File Class Breakdown.

Here’s a breakdown of its components

  1. Importing the fs (File System) Module:
    • const fs = require('fs').promises;
    • This line imports the promise-based version of the Node.js fs module, which provides functions for file system operations.
  2. File Class Definition:
    • class File { ... }
    • This is the definition of the File class.
  3. Constructor:
    • constructor(filepath) { this.filepath = filepath; }
    • The constructor takes a filepath as an argument and assigns it to the instance of the class. This filepath is used in the file operations methods.
  4. readFile Method:
    • async readFile() { ... }
    • An asynchronous method that reads the contents of the file at this.filepath.
    • It uses await fs.readFile(this.filepath, 'utf8') to read the file and return its content as a string.
    • Errors in reading the file are caught and rethrown with a custom error message.
  5. writeFile Method:
    • async writeFile(content) { ... }
    • An asynchronous method for writing content to the file at this.filepath.
    • Uses await fs.writeFile(this.filepath, content) to write the content.
    • Errors in writing are caught and rethrown with a custom error message.
  6. deleteFile Method:
    • async deleteFile() { ... }
    • An asynchronous method for deleting the file at this.filepath.
    • It uses await fs.unlink(this.filepath) to delete the file.
    • Errors in deletion are caught and rethrown with a custom error message.

 

Node.js File Class Implementation.

const fs = require('fs').promises;

class File {
  constructor(filepath) {
    this.filepath = filepath;
  }

  async readFile() {
    try {
      const content = await fs.readFile(this.filepath, 'utf8');
      return content;
    } catch(error) {
      throw new Error(`Error reading the file: ${error.message}`);
    }
  }

  async writeFile(content) {
    try {
      await fs.writeFile(this.filepath, content);
    } catch(error) {
      throw new Error(`Error writing to the file: ${error.message}`);
    }
  }

  async deleteFile() {
    try {
      await fs.unlink(this.filepath);
    } catch(error) {
      throw new Error(`Error deleting the file: ${error.message}`);
    }
  }
}

 

Usage of readFile:

const file = new File('example.txt');

file.readFile()
  .then(content => console.log(content))
  .catch(error => console.error(error));
More Examples:

Reading from a JSON file.

Below is the example how to read a JSON file from file system.

// Reading from a JSON file
const settingsFile = new File('settings.json');

settingsFile.readFile()
  .then(content => {
    const settings = JSON.parse(content);
    console.log(settings);
  })
  .catch(error => console.error(error));
// Combined with an async function
async function readExample() {
  try {
    const file = new File('example.txt');
    const content = await file.readFile();
    console.log(content);
  } catch(error) {
    console.error(error);
  }
}

readExample();

 

Usage of writeFile:

const file = new File('example.txt');

const content = 'Hello, World!';
file.writeFile(content)
  .then(() => console.log('File written successfully!'))
  .catch(error => console.error(error));
More Examples:
// Writing JSON to a file
const settingsFile = new File('settings.json');
const settings = {
  theme: 'dark',
  version: '1.0.0'
};

settingsFile.writeFile(JSON.stringify(settings))
  .then(() => console.log('Settings saved!'))
  .catch(error => console.error(error));
// Using async function to write to a file
async function writeExample() {
  try {
    const file = new File('example.txt');
    await file.writeFile('Async/Await example');
    console.log('Async write complete!');
  } catch(error) {
    console.error(error);
  }
}

writeExample();

 

Usage of deleteFile:

const file = new File('example.txt');

file.deleteFile()
  .then(() => console.log('File deleted successfully!'))
  .catch(error => console.error(error));
More Examples:
// Delete multiple files
async function deleteMultiple(files) {
  for (const filename of files) {
    const file = new File(filename);
    await file.deleteFile();
    console.log(`${filename} was deleted.`);
  }
}

deleteMultiple(['file1.txt', 'file2.txt', 'file3.txt']);
// Delete a file inside an async function
async function deleteExample() {
  try {
    const file = new File('example.txt');
    await file.deleteFile();
    console.log('File successfully deleted in async fashion.');
  } catch(error) {
    console.error(error);
  }
}

deleteExample();

 

The Node.js File class with its methods readFile, writeFile, and deleteFile provides a concise, easy-to-understand way to interact with the file system. Employing async/await syntax not only improves readability but also error handling, making it an excellent tool for developers to integrate seamless file operations in Node.js applications.