【JS】JavaScript での ファイルの読み書き

■ はじめに

* JavaScript での ファイルの読み書きをメモ。

目次

【1】JS での ファイルの読み込み
 例1:FileReader() を利用する
 例2:blob.text() を利用する
【2】JS での ファイルの書き込み

【1】JS での ファイルの読み込み

例1:blob.text() を利用する

https://write-remember.com/program/javascript/javascript_readastext/

<!DOCTYPE html>
<html>
<head>
  <title>Hello world 1</title>
</head>
<body>
  <form>
      <input id="testFile" type="file" name="file"><br>
      <textarea id="textArea"  name="txt" rows="5" cols="20"></textarea>
  </form>
  <script>
  let input = document.getElementById('testFile');
  let reader = new FileReader();
  input.addEventListener('change', () => {
      for(file of input.files){
          reader.readAsText(file, 'UTF-8');
          reader.onload = ()=> {
              document.getElementById("textArea").value = reader.result;
          };
      }
  });
  </script>
</body>
</html>

例2:blob.text() を利用する

https://www.delftstack.com/ja/howto/javascript/read-text-file-in-javascript/

<!DOCTYPE html>
<html>
  <head>
    <title>Hello world 2</title>
  </head>
  <body>
    <form>
        <input id="testFile" type="file" name="file"><br>
        <textarea id="textArea"  name="txt" rows="5" cols="20"></textarea>
    </form>

    <br>
    <pre id="output"></pre>
    <script>
     let input = document.getElementById('testFile');
     input.addEventListener('change', () => {
         for(file of input.files){
             loadFile(file);
         }
     });
     async function loadFile(file) {
       let text = await file.text();
       document.getElementById("textArea").value = text;
     }
    </script>
  </body>
</html>

【2】JS での ファイルの書き込み

* 以下のサイトなどに載っている

https://magazine.techacademy.jp/magazine/28206

サンプルより抜粋
function outputFile() {
  const textArea = document.getElementById("testData");
  const csvData = textArea.value;
  const csvArray = csvData.split('');
  const blob = new Blob(csvArray, {type:"text/plan"});

  let link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = "output.csv"
  link.click();
}

関連記事

JS で ファイル出力するCSVデータ生成ツールを作ってみる
https://dk521123.hatenablog.com/entry/2022/11/28/000000
JS で テスト用の超簡易なCSVデータ生成ツールを作ってみる
https://dk521123.hatenablog.com/entry/2022/11/23/000000
DOT言語表示ツール ~ d3-graphviz
https://dk521123.hatenablog.com/entry/2023/06/18/102448