How to read a file in TypeScript?


As a beginner-friendly programming language, TypeScript offers a variety of features to handle file operations effectively. Reading a file is a fundamental task that developers often encounter when working on projects. In this tutorial, we will explore different scenarios for reading files in TypeScript and provide clear explanations, along with syntax and code examples.

Syntax

const fileReader = new FileReader();
fileReader.onload = () => {
   const fileContent = fileReader.result as string;
   console.log(fileContent);
};

The above is the syntax to read files in typescript. We create a new FileReader instance and use its onload event handler to process the file content after it has been read. We print the file content using console.log().

Reading a Text File

To read a text file using the FileReader API, follow these steps −

Step 1: Create an HTML File Input Element

In your HTML file, create an input element of type "file" to allow the user to select the text file −

<input type="file" id="fileInput">

Step 2: Read the File

In your TypeScript code, retrieve the file from the input element and read its content using the FileReader API −

const fileInput = document.getElementById('fileInput') as HTMLInputElement;

fileInput.addEventListener('change', () => {
   const file = fileInput.files[0];
   if (file) {
      const fileReader = new FileReader();
      fileReader.onload = () => {
      const fileContent = fileReader.result as string;
      console.log(fileContent);
      };
      fileReader.readAsText(file);
   }
});

In this code, we listen for the "change" event on the file input element. When the user selects a file, we retrieve it from the files property of the input element. We then create a new FileReader instance and use its onload event handler to process the file content after it has been read. Finally, we call readAsText on the FileReader instance to read the file as text.

Output

Here, a file called Colleges.txt is uploaded as input, and its contents are printed to the console with the help of the FileReader API.

Reading a JSON File

To read a JSON file using the FileReader API, follow these steps −

Step 1: Create an HTML File Input Element

Create the HTML file input element as described in the previous scenario.

<input type="file" id="fileInput">

Step 2: Read the JSON File

Modify the TypeScript code to parse the file content as JSON −

const fileInput = document.getElementById('fileInput') as HTMLInputElement;

fileInput.addEventListener('change', () => {
   const file = fileInput.files[0];
   if (file) {
      const fileReader = new FileReader();
      fileReader.onload = () => {
         const fileContent = fileReader.result as string;
         const jsonData = JSON.parse(fileContent);
         console.log(jsonData);
         console.log(jsonData.name);
      };
      fileReader.readAsText(file);
   }
});

After reading the file content, we parse it using JSON.parse to obtain a JavaScript object representing the JSON data. In this example, we assume the JSON file has a "name" property that we log to the console.

Output

Reading a CSV File

Reading a CSV file in a web browser without using the fs module or Node.js requires additional processing. You can use the FileReader API to read the file and then parse the CSV data manually. Here's an example −

Step 1: Create an HTML File Input Element

Create the HTML file input element as described in the previous scenarios.

<input type="file" id="fileInput">

Step 2: Read and Process the CSV File

Modify the TypeScript code to read and process the CSV file content −

const fileInput = document.getElementById('fileInput') as HTMLInputElement;

fileInput.addEventListener('change', () => {
   const file = fileInput.files[0];

   if (file) {
      const fileReader = new FileReader();
      fileReader.onload = () => {
         const fileContent = fileReader.result as string;
         const rows = fileContent.split('
'); const csvData: any[] = []; for (let i = 0; i < rows.length; i++) { const columns = rows[i].split(','); csvData.push(columns); } console.log(csvData); }; fileReader.readAsText(file); } });

In this code, after reading the file content, we split it into rows by using the newline character ‘
’. We then iterate over each row and split it into columns using the comma character ‘,’. We store the CSV data in an array of arrays (csvData), where each inner array represents a row with its respective columns.

Output

Conclusion

This beginner-friendly tutorial explored alternative approaches to reading files in TypeScript. Utilizing the FileReader API allows us to handle file reading scenarios in environments where the fs module is unavailable, such as web browsers. We covered reading text files, parsing JSON files, and manually processing CSV files.

Remember, when using the FileReader API, you can retrieve the file content as a string and manipulate it as needed. For parsing structured file formats like JSON and CSV, additional processing steps may be required to extract and format the data correctly.

Updated on: 31-Aug-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements