Editors Choice

3/recent/post-list

FS Module File Handling in JS

Understanding Synchronous vs Asynchronous Operations in Node.js File System

Node.js provides both synchronous and asynchronous methods for file operations. Let's explore the differences between these approaches with decorated code examples.

The Fundamental Difference

Synchronous functions block the execution of further code until the operation completes. They are simpler to understand but can make your application unresponsive during file operations.

Asynchronous functions don't block execution. They work in the background and notify you when they're done via callbacks, promises, or events. This makes them better for performance in most cases.

Reading Files

Asynchronous File Reading

Asynchronous read example
const fs = require('fs');

// Asynchronous read - non-blocking
fs.readFile("./log.txt", "utf-8", (err, result) => {
    if(err) {
        console.error(`Error reading file: ${err}`);
    } else {
        console.log("File content:", result);
    }
});

console.log("This message appears while the file is being read");

Key Points:

  • Uses a callback function that executes when the operation completes
  • The console.log outside the callback will execute immediately
  • Better for performance as it doesn't block other operations

Synchronous File Reading

Synchronous read example
const fs = require('fs');

// Synchronous read - blocks execution
try {
    const result = fs.readFileSync("./log.txt", "utf-8");
    console.log("File content:", result);
} catch(err) {
    console.error(`Error reading file: ${err}`);
}

console.log("This message appears only after the file is read");

Key Points:

  • Execution pauses until the file is completely read
  • Uses try-catch for error handling instead of callbacks
  • Simpler to understand but can slow down your application

Writing Files

Asynchronous File Writing

Asynchronous write example
const fs = require('fs');

// Asynchronous write
fs.writeFile("./log.txt", "Hey I am written by Asynchronous Functions", (err) => {
    if(err) {
        console.error("Write failed:", err);
    } else {
        console.log("File written successfully");
    }
});

console.log("This executes while the write operation is in progress");

Synchronous File Writing

Synchronous write example
const fs = require('fs');

// Synchronous write
try {
    fs.writeFileSync("./log.txt", "Hey I am written by Synchronous Functions");
    console.log("File written successfully");
} catch(err) {
    console.error("Write failed:", err);
}

console.log("This executes only after the write completes");

Appending to Files

Asynchronous File Appending

Asynchronous append example
const fs = require('fs');

// Asynchronous append
fs.appendFile("./log.txt", "\nHey I am Appended by Asynchronous Function", (err) => {
    if(err) {
        console.error("Append failed:", err);
    } else {
        console.log("Content appended successfully");
    }
});

Synchronous File Appending

Synchronous append example
const fs = require('fs');

// Synchronous append
try {
    fs.appendFileSync("./log.txt", "\nHey I am appended by Synchronous Functions");
    console.log("Content appended successfully");
} catch(err) {
    console.error("Append failed:", err);
}

File Operations

Copying Files (Synchronous)

Synchronous copy example
const fs = require('fs');

// Synchronous copy
try {
    fs.cpSync('./log.txt', './copy-log.txt');
    console.log("File copied successfully");
} catch(err) {
    console.error("Copy failed:", err);
}

Deleting Files (Synchronous)

Synchronous delete example
const fs = require('fs');

// Synchronous delete
try {
    fs.unlinkSync("./log.txt");
    console.log("File deleted successfully");
} catch(err) {
    console.error("Delete failed:", err);
}

When to Use Each Approach

Use Asynchronous when:

  • Your application needs to remain responsive
  • You're handling multiple I/O operations
  • You're building web servers or network applications

Use Synchronous when:

  • You're writing simple scripts where blocking doesn't matter
  • You need to ensure operations complete before continuing
  • During application startup for configuration loading

Remember that Node.js excels at asynchronous operations, and that's where you'll get the best performance for most applications.

Post a Comment

0 Comments