Rajdeep Singh.

Read Locally txt File Use Fetch Method In JavaScript?

Welcome To My New Blog Post. As You Knows We Learn, How to Read Locally txt File Use Fetch Method In Javascript.

By javascript 2 min read

Let's Start It

Steps:

  1. Folder Structure
  2. Read insideFolder.txt File
  3. Read InsideFolder.txt File

Demo

Download My Project Code And Play Online On CodeSandBox Editor


If You Read Txt File, JSON File, and Any Other File Inside Javascript, use Fetch Method. Make Sure You use Live Server In Javascript.

Live Server Provide You A Http Method For Your Project. You Use Express.js, Vscode Live Server Plugin, and Any other Library.

Secondly, We Don't Import Javascript Files. When Use Fetch Method In Your Project.

import data from './read.txt';
 
// Show Error When Use Fetch Method With Import Method
fetch(data).then(function (response) {
	return response;
}).then(function (data) {
	console.log(data);
	return data.text();
}).then(function (Normal) {
	console.log(Normal);
	document.getElementById('app').innerHTML = Normal;
}).catch(function (err) {
	console.log('Fetch problem show: ' + err.message);
});

Error Look Like Your console


Fetch Method Syntax

fetch( URL, Options )

Url Option We Provide Path of Your File.

Example

http://yourdomain.com/rootFolder.txt


Folder Structure:

Inside Folder, We Read Two File:

Folder Structure


Read insideFolder.txt File

fetch('./rootFolder.txt').then(function (response) {
	return response;
}).then(function (data) {
	return data.text();
}).then(function (Normal) {
	document.getElementById('app').innerHTML = Normal;
}).catch(function (err) {
	console.log('Fetch problem show: ' + err.message);
});

Code sandbox Online Project Example My insideFolder.txt File: https://vmiy4.csb.app/src/insideFolder.txt


Read insideFolder.txt

//Read InsideFolder.txt File
fetch('./src/insideFolder.txt').then(function (response) {
	response.text().then(function (text) {
		document.getElementById('appData').innerHTML = text;
	});
});

Code sandbox Online Project Example My insideFolder.txt File: https://vmiy4.csb.app/rootFolder.txt


Demo

Download My Project Code And Play Online On CodeSandBox


Reference

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

https://www.geeksforgeeks.org/javascript-fetch-method/