Instagram
youtube
Facebook
Twitter

File System Module

Introduction

The File System module in Node.js allows you to interact with the file system on your machine. This module provides various methods to read, write, update, and delete files and directories, enabling developers to manage files efficiently. In this lesson, we will explore the File System module, its common methods, and practical examples.


Importing the File System Module

To use the File System module in your Node.js application, you need to import it using the require function:

const fs = require('fs');

Synchronous vs Asynchronous Methods

The File System module provides both synchronous and asynchronous methods. While synchronous methods block the execution of code until the operation is complete, asynchronous methods allow other operations to run while the file operation is being processed.

  • Synchronous Methods: Use when you need to ensure that an operation completes before moving on. They are easier to read but can lead to performance issues in I/O-bound applications.
  • Asynchronous Methods: Use for better performance, especially in a non-blocking environment like Node.js.

Common Methods of the File System Module

1. Reading Files

  • Asynchronous Read: Use fs.readFile() to read files without blocking the execution.

    fs.readFile('example.txt', 'utf8', (err, data) => {
        if (err) {
            console.error('Error reading file:', err);
            return;
        }
        console.log('File content:', data);
    });
    
  • Synchronous Read: Use fs.readFileSync() for synchronous file reading.

    const data = fs.readFileSync('example.txt', 'utf8');
    console.log('File content:', data);
    

2. Writing Files

  • Asynchronous Write: Use fs.writeFile() to write data to a file.

    fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
        if (err) {
            console.error('Error writing file:', err);
            return;
        }
        console.log('File has been written!');
    });
    
  • Synchronous Write: Use fs.writeFileSync() for synchronous writing.

    fs.writeFileSync('output.txt', 'Hello, Node.js!');
    console.log('File has been written synchronously!');
    

3. Appending to Files

  • Asynchronous Append: Use fs.appendFile() to append data to a file.

    fs.appendFile('output.txt', '\nAppending this line.', (err) => {
        if (err) {
            console.error('Error appending to file:', err);
            return;
        }
        console.log('Data has been appended!');
    });
    

4. Deleting Files

  • Asynchronous Delete: Use fs.unlink() to delete a file.

    fs.unlink('output.txt', (err) => {
        if (err) {
            console.error('Error deleting file:', err);
            return;
        }
        console.log('File has been deleted!');
    });
    

5. Creating Directories

  • Asynchronous Directory Creation: Use fs.mkdir() to create a new directory.

    fs.mkdir('new_directory', (err) => {
        if (err) {
            console.error('Error creating directory:', err);
            return;
        }
        console.log('Directory has been created!');
    });
    

6. Reading Directory Contents

  • Asynchronous Directory Read: Use fs.readdir() to list files in a directory.

    fs.readdir('some_directory', (err, files) => {
        if (err) {
            console.error('Error reading directory:', err);
            return;
        }
        console.log('Files in directory:', files);
    });
    

Error Handling

Proper error handling is crucial when working with the File System module. Always check for errors in the callback functions to prevent your application from crashing.


Conclusion

The File System module in Node.js provides powerful methods for interacting with the file system. By understanding how to read, write, delete, and manage files and directories, you can build applications that effectively handle data storage and manipulation.