Advertisement
vvccs

wt15_filehandle

Oct 13th, 2024
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require('fs');
  2.  
  3. // Function to read a file
  4. function readFile(filePath) {
  5.     return new Promise((resolve, reject) => {
  6.         fs.readFile(filePath, 'utf8', (err, data) => {
  7.             if (err) {
  8.                 reject(err); // Reject the promise if there's an error
  9.             } else {
  10.                 resolve(data); // Resolve the promise with the file data
  11.             }
  12.         });
  13.     });
  14. }
  15.  
  16. // Main function to execute the file reading
  17. async function main() {
  18.     const filePath = 'example.txt'; // Change this to an invalid path to test error handling
  19.     try {
  20.         const data = await readFile(filePath);
  21.         console.log('File Content:', data);
  22.     } catch (error) {
  23.         console.error('Error reading file:', error.message);
  24.     }
  25. }
  26.  
  27. // Execute the main function
  28. main();
  29.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement