戻る

fetchでテキストファイルを読み込む方法
fetch APIを使ってテキストファイルを読み込む処理

サンプル
[読み込んだテキストの表示]




copy
const b1 = document.getElementById("btn1");
const b2 = document.getElementById("btn2");
b1.addEventListener("click", () => 
{
	loadText();
});
b2.addEventListener("click", () => 
{
	clearText();
});
function loadText()
{
	fetch('js19_txt_jp.txt')
	.then(response => 
	{
		if (!response.ok)
		{
			throw new Error('Network response was not ok');
		}
		return response.text();
	})
	.then(text => 
	{
		// テキストデータ 'text' を処理
		const d1 = document.getElementById("text");
		d1.textContent = text;
	})
	.catch(error => 
	{
		// エラー処理
		console.error('There has been a problem with your fetch operation:', error);
	});
}
function clearText()
{
	const d1 = document.getElementById("text");
	d1.textContent = "";
}
解説
fetch('js19_txt_jp.txt')
fetch関数は、HTTPリクエストを送信し、その結果を表すPromiseに返します。
Promiseが解決した(リクエストが成功した場合)ときにthenメソッドが呼び出されます。
そして、thenに渡されたコールバック関数が実行されます。
thenに渡すコールバック関数の引数には、fetchの結果を表すResponseオブジェクトが渡されます。
このResponseオブジェクトには、レスポンスのステータスコード、ヘッダー、ボディなどの情報が含まれています。

.then(response =>
{
...
})
この例ではthenの引数名に「response」を設定しています。
thenメソッドの引数名は、自由に設定できます。
また、変数名として有効なものであれば何でも構いません。

fetch関数からのレスポンスを受け取り、処理を実行します。
response.okでHTTPステータスコードが200番台かどうかを確認します。
※エラーの場合はthrow new Error()でエラーを発生させ、catch()ブロックで処理します。

response.text()でレスポンスボディをテキストデータとして読み込みます。
※xxx.text()の「.text()」がテキストを読み込むため、用意されたメソッドです。
Promiseを返すため、さらにthen()で処理を続けます。

.then(text =>
{
...
})
「return response.text();」の結果をthenの引数名「text」に渡します。
ここのtext変数名は別の名前でも構いません。
この例では、textareaタグにテキストデータを表示しています。

.catch(error =>
{
...
});
fetch()の実行中、またはthen()内の処理でエラーが発生した場合に実行されます。
エラーメッセージをコンソールに表示する例です。

fetchを非同期処理で実行するため、thenやcatch()で処理をつなげる必要があります。


戻る
back

How to read a text file with fetch
Reading a text file using the fetch API

sample
[Show loaded text]




copy
const b1 = document.getElementById("btn1");
const b2 = document.getElementById("btn2");
b1.addEventListener("click", () => 
{
	loadText();
});
b2.addEventListener("click", () => 
{
	clearText();
});
function loadText()
{
	fetch('js19_txt_en.txt')
	.then(response => 
	{
		if (!response.ok)
		{
			throw new Error('Network response was not ok');
		}
		return response.text();
	})
	.then(text => 
	{
		// Process text data 'text'
		const d1 = document.getElementById("text");
		d1.textContent = text;
	})
	.catch(error => 
	{
		// Error Handling
		console.error('There has been a problem with your fetch operation:', error);
	});
}
function clearText()
{
	const d1 = document.getElementById("text");
	d1.textContent = "";
}
Explanation
fetch('js19_txt_en.txt')
The fetch function sends an HTTP request and returns a Promise representing the result.
The then method is called when the Promise is resolved (if the request is successful).
Then, the callback function passed to then is executed. 
The argument of the callback function passed to then is a Response object representing the fetch result.
This Response object contains information such as the response status code, headers, and body. 

.then(response =>
{
...
})
In this example, the argument name of then is set to "response".
You can freely set the argument name of the then method.
Also, it can be anything as long as it is a valid variable name.

Receive the response from the fetch function and execute the process.
Check whether the HTTP status code is in the 200 range with response.ok.
*If there is an error, throw new Error() to generate an error and handle it in the catch() block.

Read the response body as text data with response.text().
*The ".text()" in xxx.text() is a method provided to read text.
Since it returns a Promise, processing continues with then().

.then(text =>
{
...
})
The result of "return response.text();" is passed to the argument name "text" of then.
The text variable name here can be a different name.
In this example, text data is displayed in the textarea tag.

.catch(error =>
{
...
});
Executed if an error occurs during execution of fetch() or processing within then().
An example of displaying an error message in the console. 

Since fetch is executed asynchronously, it is necessary to connect the processing with then or catch().


back



著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。