With the introduction of async/await
in Node.js, handling asynchronous operations has become more readable and maintainable compared to traditional callback-based methods.
javascriptCopy code// Example using async/await
const fs = require('fs').promises;
async function readFile(filePath) {
try {
const data = await fs.readFile(filePath, 'utf8');
console.log(data);
} catch (err) {
console.error('Error reading file:', err);
}
}
readFile('./example.txt');
Explanation:
fs.promises
provides promise-based versions of filesystem methods.async/await
is used to handle the asynchronousreadFile
method more cleanly.
Leave a Reply