Reading files asynchronously lets your program keep working while waiting for the file to load. This avoids freezing or slowing down your app.
Reading files asynchronously with callbacks in 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.
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); } });
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); } });
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.
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); } });
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.
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.