0
0
Node.jsframework~5 mins

Reading files asynchronously with callbacks in Node.js

Choose your learning style9 modes available
Introduction

Reading files asynchronously lets your program keep working while waiting for the file to load. This avoids freezing or slowing down your app.

When you want to read a file but keep your app responsive.
When reading large files that might take time to load.
When you want to handle file reading errors without crashing.
When you want to process file data only after it has fully loaded.
Syntax
Node.js
const fs = require('fs');

fs.readFile('path/to/file', 'utf8', (err, data) => {
  if (err) {
    // handle error
  } else {
    // use the file data
  }
});

The callback function has two parameters: err for errors and data for the file content.

Always check for errors before using the data to avoid crashes.

Examples
This reads 'example.txt' as text and prints its content or an error message.
Node.js
const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
  } else {
    console.log('File content:', data);
  }
});
This reads a JSON file, parses it, and logs the object.
Node.js
const fs = require('fs');

fs.readFile('data.json', 'utf8', (err, data) => {
  if (err) {
    console.error('Failed to read JSON file:', err);
  } else {
    const jsonData = JSON.parse(data);
    console.log('Parsed JSON:', jsonData);
  }
});
Sample Program

This program reads the file 'greeting.txt' asynchronously. If the file is read successfully, it prints its content. If there is an error (like file not found), it prints an error message.

Node.js
const fs = require('fs');

fs.readFile('greeting.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Could not read file:', err.message);
  } else {
    console.log('File says:', data);
  }
});
OutputSuccess
Important Notes

Always provide the correct file path and encoding (like 'utf8') to read text files properly.

Asynchronous reading means your program does not wait and can do other things while the file loads.

Callbacks help you handle the file content only after it is ready.

Summary

Use fs.readFile with a callback to read files without stopping your program.

Check for errors inside the callback before using the file data.

Asynchronous reading keeps your app fast and responsive.