テキストファイルを読み込む

 JavaScriptでテキストファイルを読み込む方法はいくつかあります。以下に代表的な方法を3つ紹介します。


1. File APIを使用してローカルファイルを読み込む

ユーザーがファイルを選択する場合に使用します。

document.getElementById('fileInput').addEventListener('change', function(event) {
  const file = event.target.files[0];
  const reader = new FileReader();

  reader.onload = function(e) {
    console.log(e.target.result); // テキスト内容を表示
  };

  reader.readAsText(file);
});

HTML例:

<input type="file" id="fileInput" />

2. Fetch APIを使用してサーバー上のテキストファイルを読み込む

外部リソースからテキストファイルを取得する場合に使用します。

fetch('example.txt')
  .then(response => {
    if (!response.ok) {
      throw new Error('ファイルの読み込みに失敗しました');
    }
    return response.text();
  })
  .then(data => {
    console.log(data); // テキスト内容を表示
  })
  .catch(error => {
    console.error(error);
  });

3. Node.jsでファイルを読み込む

サーバーサイドでファイルを読み込む場合に使用します。

const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('ファイルの読み込みに失敗しました:', err);
    return;
  }
  console.log(data); // テキスト内容を表示
});

これらの方法を使い分けることで、用途に応じたテキストファイルの読み込みが可能です!

コメント