DEV Community

Jonathan Powell
Jonathan Powell

Posted on

Retrieving Files with the 'fetch' API

Javascript's Fetch API is usually used to get data from an API. But it can also be used to retrieve files!

Fetch a .txt file

The Response object that is returned from 'fetch', has a few methods that let you retrieve the data returned from the request

  • .json(): returns json
  • .text(): returns a string of all the text in the response

We use the .text() method to get a string of the text from a file.

fetch('example.txt')
.then(response => response.text()) 
.then(textString => {
    console.log(textString);
});
Enter fullscreen mode Exit fullscreen mode

The process is identical if we wanted to retrieve a .csv file and do something with the data that's in the file. But we have some extra code to break up the file into rows.

fetch('example.csv')
.then(response => response.text()) 
.then(csvString => {
    //Split the csv into rows
    const rows = csvString.split('\n');
    for (row of rows) {
    //Split the row into each of the comma separated values
        console.log(row.split(","));
    }
});
Enter fullscreen mode Exit fullscreen mode

Look at this GitHub repo for example code:
https://github.com/jpowell96/readFilesWithFetch

Top comments (0)