Ⅰ. はじめに
タイトルの通り「WebブラウザのJavaScriptでテキストファイルの文字コードを取得する方法」です。
Ⅱ. 手順
1. サンプルプログラムを書く
<html> <body> <input type="file" id="file001" accept="text/plain"> <script> const file001 = document.getElementById('file001') file001.addEventListener('change', onFileChanged) function onFileChanged (event) { const file = file001.files[0] const reader = new FileReader() reader.onload = async (e) => { // テキストファイルの文字コードを取得する let text = e.target.result.toString() let bytes = Encoding.stringToCode(text) const encoding = Encoding.detect(bytes) console.log(encoding) } reader.readAsBinaryString(file) } </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/encoding-japanese/2.0.0/encoding.min.js"></script> </body> </html>
実行結果