DEV Community

Andrew Kao
Andrew Kao

Posted on

Reading a File through Related Path Using Fetch API

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));
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (4)

Collapse
 
rizqyhi profile image
Rizqy H.

Hi Andrew,
I don't get which part of your code working with local files. As far as I know, that code is fetching a file with relative path to where the code is located. But how would it work with local file owned by user of the app?

Collapse
 
andykao1213 profile image
Andrew Kao

Hi Rizqy,
Thanks for your reply. You're right, this approach can only get the file with the relative path.
Getting actual local files should use something like FileReader.
I think I'll change the title for it may confuse others.

Collapse
 
saeedjhn profile image
saeedjhn

In node err:

TypeError: Failed to parse URL from ./countries.json
at Object.fetch (node:internal/deps/undici/undici:11522:11) {
[cause]: TypeError [ERR_INVALID_URL]: Invalid URL
at new NodeError (node:internal/errors:399:5)
at new URL (node:internal/url:743:13)
at new Request (node:internal/deps/undici/undici:7082:25)
at fetch2 (node:internal/deps/undici/undici:10661:25)
at Object.fetch (node:internal/deps/undici/undici:11520:18)
at fetch (node:internal/process/pre_execution:239:25)
at file:///home/leader/Srv/NODE/course/node-test/runner.js:7:1
at ModuleJob.run (node:internal/modules/esm/module_job:192:25) {
input: './countries.json',
code: 'ERR_INVALID_URL'

solution?

Collapse
 
samerkassem profile image
Samerkassem • Edited

Hi Adrew,

I am following this same code: stackoverflow.com/questions/613837...

Apparently stackoverflow fellows didn't like my question, I think they didn't understand the problem :(

I have no idea what's wrong: I have placed the file in the root client director, I have placed also the file in the same folder of the script, it failed on both to find them.