DEV Community

Jonathan Powell
Jonathan Powell

Posted on

8 1

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

API Trace View

Struggling with slow API calls? πŸ‘€

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more β†’

Top comments (0)

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more