日本語

Reading Shift_JIS Files in React Without Mojibake

​​React​Encoding API,File API,Playwright,TypeScript

Reading a Shift_JIS file with file.text() produces mojibake because this method always reads the contents as UTF-8. Get the file as raw bytes, pass them to TextDecoder with 'shift_jis', and you get a correctly displayed string. If you keep the bytes in state, you can switch the encoding without selecting the file again.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. The test file was made by converting UTF-8 text to CP932 with iconv (glibc 2.39). I type-checked the .tsx with tsc, built it for production with esbuild, and checked the display by selecting the file with Playwright. I did not test Firefox, Safari, smartphone browsers, EUC-JP or ISO-2022-JP files, or large files.

A screen with a file picker and an encoding selector, and below them a box showing the loaded string. When memo-sjis.txt is selected with the encoding still set to UTF-8, the string is full of symbols such as "�". When the encoding is switched to Shift_JIS, it displays correctly, showing a Japanese label meaning "inventory memo" and a line meaning "① apple 120 yen". With "auto", it also displays as Shift_JIS. A band at the bottom shows the number of the operation. The labels in the image are in Japanese.
Selecting a Shift_JIS file and switching the encoding. The display turns pink only at the moment it changes

file.text() always reads the contents as UTF-8

MDN's description of Blob.text() says the contents are always treated as UTF-8. You cannot specify an encoding as an argument either.

The test file memo-sjis.txt is a 73-byte file made by converting the following five lines to CP932 with iconv and saving the result.

text
在庫メモ
①りんご 120円
②みかん 80円
㈱髙﨑商店〜アイウ
C:\data\メモ.txt

Reading it in Chromium with file.text() gives the following.

text
�݌Ƀ���
�@��񂲁@120�~
�A�݂���@80�~
���������X�`���
C:\data\����.txt

Bytes that are not valid UTF-8 became the replacement character "�". ASCII characters (120 and C:\data\) are written as the same single bytes in UTF-8, so they were read correctly.

Read it with TextDecoder and 'shift_jis'

To specify the encoding, get the file as raw bytes with arrayBuffer(), then convert them to a string with TextDecoder.

ts
const bytes = await file.arrayBuffer();
const text = new TextDecoder('shift_jis').decode(bytes);

The older FileReader.readAsText() also accepts an encoding as its second argument. The result of readAsText(file, 'shift_jis') was a correct string, the same as with TextDecoder.

The names (labels) you can pass to TextDecoder are defined in the label table of the WHATWG Encoding Standard. There are eight Shift_JIS labels, including shift_jis, sjis, windows-31j, and ms932, and all of them give the same Shift_JIS decoder. Testing in Chromium gave these results.

text
shift_jis → shift_jis
Shift_JIS → shift_jis
sjis → shift_jis
shift-jis → shift_jis
windows-31j → shift_jis
ms932 → shift_jis
cp932 → RangeError
x-sjis → shift_jis
ms_kanji → shift_jis
csshiftjis → shift_jis

The right side is the encoding value of the TextDecoder that was created. Case does not matter. cp932 is not in the table, so it threw a RangeError.

Keep the bytes and let the user switch the encoding

You cannot know whether a selected file is Shift_JIS or UTF-8 until you read it. So when a file is selected, store its bytes in state, and convert them to a string each time the encoding changes. Changing the encoding does not require reading the file again.

The conversion is a function separate from React.

ts
export type Choice = 'auto' | 'utf-8' | 'shift_jis';

export type Decoded = { text: string; encoding: 'UTF-8' | 'Shift_JIS' };

export function decodeBytes(bytes: Uint8Array, choice: Choice): Decoded {
  if (choice === 'utf-8') return { text: new TextDecoder('utf-8').decode(bytes), encoding: 'UTF-8' };
  if (choice === 'shift_jis') return { text: new TextDecoder('shift_jis').decode(bytes), encoding: 'Shift_JIS' };
  // Auto: if it is not valid UTF-8 (fatal throws a TypeError), read it as Shift_JIS
  try {
    return { text: new TextDecoder('utf-8', { fatal: true }).decode(bytes), encoding: 'UTF-8' };
  } catch {
    return { text: new TextDecoder('shift_jis').decode(bytes), encoding: 'Shift_JIS' };
  }
}

In "auto", the file is first read with a UTF-8 TextDecoder that has fatal: true. As described in MDN's TextDecoder() description, when fatal is false (the default), unreadable bytes are only replaced with the replacement character and no error is raised. When it is true, a TypeError is thrown. In the test environment, reading memo-sjis.txt threw a TypeError, and only then was the file read again as Shift_JIS.

The component is as follows.

tsx
import { useId, useMemo, useState } from 'react';
import { decodeBytes, type Choice } from './decode';

type Loaded = { name: string; bytes: Uint8Array };

export function TextFileViewer() {
  const [loaded, setLoaded] = useState<Loaded | null>(null);
  const [choice, setChoice] = useState<Choice>('auto');
  const fileId = useId();
  const choiceId = useId();

  // Keep the raw bytes and decode them again when the encoding changes
  const decoded = useMemo(() => (loaded ? decodeBytes(loaded.bytes, choice) : null), [loaded, choice]);

  async function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    const bytes = new Uint8Array(await file.arrayBuffer());
    setLoaded({ name: file.name, bytes });
  }

  return (
    <div className="viewer">
      <p>
        <label htmlFor={fileId}>テキストファイル</label>
        <input id={fileId} type="file" accept=".txt,.csv,text/plain,text/csv" onChange={handleChange} />
      </p>
      <p>
        <label htmlFor={choiceId}>文字コード</label>
        <select id={choiceId} value={choice} onChange={(e) => setChoice(e.target.value as Choice)}>
          <option value="auto">自動(UTF-8 → Shift_JIS)</option>
          <option value="utf-8">UTF-8</option>
          <option value="shift_jis">Shift_JIS</option>
        </select>
      </p>
      {loaded && decoded && (
        <section aria-live="polite">
          <p className="name">
            {loaded.name}({loaded.bytes.length}バイト、<span className="encoding">{decoded.encoding}</span>で表示)
          </p>
          <pre className="text">{decoded.text}</pre>
        </section>
      )}
    </div>
  );
}

The state holds two things: the name and bytes of the loaded file (loaded), and the selected encoding (choice). The displayed string is built from these two with useMemo. Changing the <select> changes only choice, and the bytes already in hand are passed to decodeBytes() again.

In the test environment, I changed the combination of file and encoding and checked the display. Shift_JIS files displayed correctly in "auto" and "Shift_JIS". In "UTF-8", they showed the same mojibake as file.text(). memo-utf8.txt (103 bytes), saved as UTF-8, was detected as UTF-8 in "auto" and displayed correctly.

Conversely, reading a UTF-8 file as Shift_JIS produces a different kind of mojibake, like this.

text
蝨ィ蠎ォ繝。繝「
竭�繧翫s縺斐120蜀�
竭。縺ソ縺九s縲80蜀�
繹ア鬮呻ィ大膚蠎励懶スア�イ�ウ
C:\data\繝。繝「.txt

In a UTF-8 file read as Shift_JIS, many parts turn into kanji and half-width katakana, and some lines contain no "�" at all. This is why auto-detection tries UTF-8 first.

Point

Auto-detection only checks whether the bytes are valid UTF-8. This function treats every file that is not valid UTF-8 as Shift_JIS. Files in other encodings cannot be displayed correctly by this component, no matter which option is chosen.

① and rare kanji decode correctly, but 〜 becomes a full-width tilde

Symbols like ① and ㈱, and rare kanji such as U+9AD9 and U+FA11, could not be converted to SHIFT_JIS with the iconv in the test environment, but they could be converted to CP932.

text
①  SHIFT_JIS: NG  CP932: 87 40
㈱  SHIFT_JIS: NG  CP932: 87 8a
髙  SHIFT_JIS: NG  CP932: fb fc
﨑  SHIFT_JIS: NG  CP932: fa b1
〜  SHIFT_JIS: 81 60  CP932: 81 60
~  SHIFT_JIS: NG  CP932: 81 60
ア  SHIFT_JIS: b1  CP932: b1

The browser's TextDecoder('shift_jis') can also read these characters when they are written in CP932. The jis0208 table of the Encoding Standard, which the Shift_JIS decoder uses, includes characters such as ① (entry 1128). In the test environment, ① was read as U+2460, ㈱ as U+3231, the first rare kanji as U+9AD9, the second rare kanji as U+FA11, and the half-width katakana letter A (U+FF71) from the sample line was read correctly.

Be careful with 〜. The original UTF-8 text had the wave dash (U+301C) "〜", but the string read back from the Shift_JIS file contained the full-width tilde (U+FF5E) "~". As the table above shows, CP932 writes both as the same bytes, 81 60. The Shift_JIS decoder looks up 81 60 as entry 32 in the jis0208 table, and entry 32 is U+FF5E. So the string read from the file does not match '〜' (U+301C) written in the code, and a search for it finds nothing.

The \ (byte 5c) in the last line of the file is treated as an ASCII byte by the Encoding Standard's Shift_JIS decoder. In the test environment, it became U+005C, a backslash.

​Posted by 86