Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

Comparing File Reading in Node.js: Native fs Module vs. then-fs Package

Tools 2

Native fs Module in Node.js

The built-in fs module in Node.js provides file system operations using callback functions. Here's an example of reading a file:

const fs = require('fs');

fs.readFile('./data/file.txt', 'utf8', (error, data) => {
  if (error) {
    console.error('Error reading file:', error);
  } else {
    console.log('File content:', data);
  }
});

This approach uses a callback pattern, where the function executes asynchronously and returns results or errors via the callbcak.

then-fs Package for Promise-Based File Reading

To use Promise-based methods for file reading, install the then-fs package: npm install then-fs. This package wraps fs fnuctions to return Promises.

const thenFs = require('then-fs');

thenFs.readFile('./data/file.txt', 'utf8')
  .then(content => {
    console.log('File content:', content);
  })
  .catch(error => {
    console.error('Error reading file:', error);
  });

Chaining .then() methods allows sequential file reads, avoiding callback nesting:

thenFs.readFile('./data/file1.txt', 'utf8')
  .then(data1 => {
    console.log('First file:', data1);
    return thenFs.readFile('./data/file2.txt', 'utf8');
  })
  .then(data2 => {
    console.log('Second file:', data2);
    return thenFs.readFile('./data/file3.txt', 'utf8');
  })
  .then(data3 => {
    console.log('Third file:', data3);
  })
  .catch(error => {
    console.error('Error in chain:', error);
  });

Using .catch() handles errors in Promise chains, enabling continued execution after an error:

thenFs.readFile('./data/file1.txt', 'utf8')
  .catch(error => {
    console.log('Caught error:', error.message);
    return null; // Continue chain with a fallback value
  })
  .then(result => {
    console.log('Result after catch:', result);
    return thenFs.readFile('./data/file2.txt', 'utf8');
  })
  .then(data => {
    console.log('Second file data:', data);
  });

Related Articles

Efficient Usage of HTTP Client in IntelliJ IDEA

IntelliJ IDEA incorporates a versatile HTTP client tool, enabling developres to interact with RESTful services and APIs effectively with in the editor. This functionality streamlines workflows, replac...

Installing CocoaPods on macOS Catalina (10.15) Using a User-Managed Ruby

System Ruby on macOS 10.15 frequently fails to build native gems required by CocoaPods (for example, ffi), leading to errors like: ERROR: Failed to build gem native extension checking for ffi.h... no...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.