How to Use the JavaScript Fetch API to Retrieve Text From TXT and JSON Files

Photo by AltumCode on Unsplash

How to Use the JavaScript Fetch API to Retrieve Text From TXT and JSON Files

The Fetch API is usually used for fetching resources across the network with its global fetch() method. But did you know you can use it to read the contents from local JSON and TXT files too?

When we are presented with a large set of data that we need to have available in our code, we would probably go crazy trying to process it line by line. Besides, as programmers, we want to make our life easier, not harder!

Short JavaScript Fetch API Overview

The JavaScript Fetch API is an interface that is able to access and manipulate parts of the protocol and fetch resources asynchronously. It is designed around the use of Promises, which simplifies handling asynchronous operations. Instead of using callbacks, Fetch returns a Promise that resolves to the Response object to represent the completion or failure of the request.

The Fetch API is quite versatile and can be used to make various types of requests (GET, POST, PUT, DELETE, etc.). It also supports custom headers, request and response types, and can handle different data formats such as JSON, FormData, and more. It supports cross-origin requests, which means that we can make requests to different domains. However, due to the same-origin policy enforced by browsers, we may encounter issues when making requests to a different domain. CORS (Cross-Origin Resource Sharing) headers need to be set on the server to allow or restrict such cross-origin requests.

The fetch() Method and Response.text()

In order to make a request and fetch a resource, we can use the global fetch() method which returns a Promise that resolves to the Response object once the response is available.

When it comes to my app, I needed to get an array of strings. In order to achieve that, I had to read 1000 lines of text from a file called data.txt, split them by newline and push them into an array.

In order to access the contents of the data.txt file, we first need to feed the fetch() method the path to the resource we want to fetch:

fetch('data.txt')

We need to keep in mind that a fetch() Promise can only reject when there is a network error, but never rejects HTTP errors, such as 404. In order to handle such cases, we must add a then() handler to check the response status.

.then((response) => {
    if (response.status !== 200) {
      alert(`Error: Unable to load preview, HTTP response ${response.status}.`);
    }
})

Once the Response object is retrieved, we are able to take advantage of its Response.text() method. Response.text() returns a Promise that resolves with a text representation of the response body that resolves with a String, which is always decoded using UTF-8.

.then((response) => {
    if (response.status !== 200) {
      alert(`Error: Unable to load preview, HTTP response ${response.status}.`);
    }
    response.text();
})

Now it's time to handle the successful event. In my case, that meant splitting the array by newline and passing that array as an argument to a function called getCalibrationValue():

.then((data) => {
    const arr = data.split(/\r|\n/);
    getCalibrationVal(arr);
})

If a Promise rejects, or throws an error, at any stage of the promise chain, it can be caught by the catch() block:

.catch((error) => alert(`Error: ${error}`));

Handling JSON Files

In case the data we are fetching are in JSON format (we can get the file content type from response headers: response.headers.get('Content-Type')), we need to call the Response.json() method instead:

.then((response) => response.json())

Code Snippet

fetch('data.txt')
  .then((response) => {
    if (response.status !== 200) {
      alert(`Error: Unable to load preview, HTTP response ${response.status}.`);
    }
    response.text();
  })
  .then((data) => {
    const arr = data.split(/\r|\n/);
    getCalibrationVal(arr);
  })
  .catch((error) => alert(`Error: ${error}`));

I hope this article has helped you understand how data from local files can be fetched with the help of Fetch API! The inspiration for writing it was Day 1 of the Advent of Code challenge. Once I finished writing the algorithm, I knew my solution was right thanks to the testing data provided, but the last step of completing the challenge was to sum data from the above-mentioned file with a thousand lines of strings.

I am still fairly new to JavaScript and will be greatly appreciative of any constructive feedback, so don't hesitate to comment any suggestions you might have either in the comment section of this article, or get in touch with me on social media (links are in the header of this page). Thank you for reading!