Reading a File through Related Path Using Fetch API
Andrew Kao
Posted on December 1, 2019
In some cases, we may want to read files (.csv, .txt ….) while building a web app. There are several ways to do this. Today, I am going to share an easy way to read these files using Fetch API.
What is Fetch?
Before we start, let's figure out what Fetch API exactly is. According to MDN, Fetch is described as below:
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
Fetch is an API to request data through networks using Http request, and we could also use this to request local files!
Start Fetching Local Data!
fetch('../static/test.txt', {mode: 'no-cors'})
.then(response => response.text())
.then(data=> console.log(data))
.catch(error => console.error(error));
Quite easy doesn't it? Now we can get our file in type of string
since we use the method text()
. If we are reading a JSON file, we can use json()
. See more method we can handle with the response here.
Posted on December 1, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024