TypeScript file Handling with Error Catching
TypeScript Error Handling : Exercise-4 with Solution
Write a TypeScript program that opens a non-existent file using the Node.js `fs` module. Implement error handling to catch file-not-found exceptions and display an error message.
Sample Solution:
TypeScript Code:
import * as fs from 'fs';
const filePath = 'test.txt';
fs.readFile(filePath, 'utf8', (error, data) => {
if (error) {
if (error.code === 'ENOENT') {
console.error(`File not found: ${filePath}`);
} else {
console.error(`Error reading file: ${error.message}`);
}
} else {
console.log(`File content: ${data}`);
}
});
Explanations:
In the exercise above -
- First, import the "fs" module to work with file operations.
- Specify the 'filePath' variable with the path to a non-existent file.
- Use 'fs.readFile' to attempt reading the file asynchronously.
- In the callback function, we check for errors using if (error). If an error occurs, we check if the error code is 'ENOENT', which indicates a file-not-found error. In this case, we display a custom error message. If it's another type of error, we display the error message.
- Finally, If no error occurs, we display the file content.
Output:
File not found: test.txt
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript integer parsing with Error Handling.
Next: Custom TypeScript Validation Errors.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/typescript-exercises/typescript-error-handling-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics