Your Page Title
🔍

    WORKING WITH THE FILE SYSTEM MODULE

    READING MODULES

    In Node.js, reading files from the file system is handled through the built-in fs (File System) module. This module enables interaction with the local disk, such as reading, writing, or modifying files and directories. It supports both synchronous and asynchronous operations.

    Reading Files: Two Main Methods

    1. Asynchronous – Preferred for non-blocking I/O, especially in production environments.
      • Method: fs.readFile(path, [options], callback)
      • Use Case: Doesn’t halt execution; suitable for high-performance applications.
    2. Synchronous – Blocks execution until the file is read.
      • Method: fs.readFileSync(path, [options])
      • Use Case: Simpler for quick scripts or when blocking is acceptable.

    EXAMPLE CODE

    #Asynchronous File Read

    const fs = require(‘fs’);

    fs.readFile(‘./example.txt’, ‘utf8’, (err, data) => {
    if (err) {
    console.error(‘Error reading file:’, err);
    return;
    }
    console.log(‘File contents:’, data);
    });

    #Synchronous File Read

    const fs = require(‘fs’);

    try {
    const data = fs.readFileSync(‘./example.txt’, ‘utf8’);
    console.log(‘File contents:’, data);
    } catch (err) {
    console.error(‘Error reading file:’, err);
    }

    WRITING MODULES

    Modules in Node.js provide a structured way to organize and reuse code effectively. By segmenting functionality into discrete units, developers can maintain clarity, scalability, and flexibility in application design. Whether working with built-in utilities like fs or crafting custom solutions, module systems form the foundation of modern Node.js development. Understanding patterns and best practices empowers efficient and maintainable backend architecture.

    Writing Files: Two Main Methods

    1. Asynchronous – Performs writing without blocking the event loop.
      • Method: fs.writeFile(path, data, [options], callback)
      • Use Case: Ideal for non-blocking applications or concurrent writes.
    2. Synchronous – Writes data and halts further execution until completion.
      • Method: fs.writeFileSync(path, data, [options])
      • Use Case: Suitable for simple tasks or setup scripts where blocking is acceptable.

    EXAMPLE CODE

    #Asynchronous File Write

    const fs = require(‘fs’);

    const content = ‘This is sample content written asynchronously.’;

    fs.writeFile(‘./output.txt’, content, ‘utf8’, (err) => {
    if (err) {
    console.error(‘Error writing file:’, err);
    return;
    }
    console.log(‘File written successfully.’);
    });

    #Synchronous File Write

    const fs = require(‘fs’);

    const content = ‘This is sample content written synchronously.’;

    try {
    fs.writeFileSync(‘./output.txt’, content, ‘utf8’);
    console.log(‘File written successfully.’);
    } catch (err) {
    console.error(‘Error writing file:’, err);
    }

    DELETING MODULES

    In Node.js, deleting files from the local file system is handled through the built-in fs module. This module offers both synchronous and asynchronous methods to remove files programmatically. Understanding how to safely perform file deletions is essential for tasks like log cleanup, temporary file management, or handling user uploads. The following approaches illustrate how to implement deletion using Node.js.

    Deleting Files: Two Main Methods

    1. Asynchronous Deletion
      • Method: fs.unlink(path, callback)
      • Use Case: Non-blocking, suitable for production environments and concurrent tasks.
    2. Synchronous Deletion
      • Method: fs.unlinkSync(path)
      • Use Case: Useful for scripts or scenarios where blocking is acceptable.

    EXAMPLE CODE

    #Asynchronous File Deletion

    const fs = require(‘fs’);

    fs.unlink(‘./output.txt’, (err) => {
    if (err) {
    console.error(‘Error deleting file:’, err);
    return;
    }
    console.log(‘File deleted successfully.’);
    });

    #Synchronous File Deletion

    const fs = require(‘fs’);

    try {
    fs.unlinkSync(‘./output.txt’);
    console.log(‘File deleted successfully.’);
    } catch (err) {
    console.error(‘Error deleting file:’, err);
    }

    DIFFERENCE BETWEEN SYNCHRONOUS VS ASYNCHRONOUS FILE OPERATIONS

    ASPECTSYNCHRONOUSASYNCHRONOUS
    EXECUTION FLOWBlocks the event loop until operation completesNon-blocking; continues execution while operation proceeds
    PERFORMANCESlower for large-scale or I/O-heavy applicationsFaster and more scalable under high load
    METHOD PREFIXMethods end with Sync (e.g., fs.readFileSync)Methods without Sync (e.g., fs.readFile)
    ERROR HANDLINGUses try...catch blocksUses callbacks or Promises (err argument)
    USE CASESuitable for small scripts or startup routinesRecommended for production apps and concurrent workloads
    THREADING IMPACTBlocks the single-threaded event loopOffloads I/O to libuv thread pool
    CALLBACK REQUIREMENTNot required, returns result immediatelyRequires callback or async/await for result handling
    USER EXPERIENCE IMPACTMay cause delays or freezing in interactive appsKeeps UI or server responsive