Encoding API を使用した ArrayBuffer から文字列への変換を容易に

2 年以上前に、Renato Mangini が未加工の ArrayBuffers とそのデータの対応する文字列表現を変換する方法について説明しました。投稿の最後に、Renato 氏は、変換を処理するための公式の標準 API の草案を作成中であると述べています。仕様が成熟し、FirefoxGoogle Chrome の両方で、TextDecoder インターフェースと TextEncoder インターフェースがネイティブにサポートされるようになりました。

このライブサンプル(下記参照)で紹介しているように、Encoding API を使用すると、作業する必要がある多くの標準エンコードの種類を問わず、未加工のバイトとネイティブの JavaScript 文字列を簡単に変換できます。

<pre id="results"></pre>

<script>
    if ('TextDecoder' in window) {
    // The local files to be fetched, mapped to the encoding that they're using.
    var filesToEncoding = {
        'utf8.bin': 'utf-8',
        'utf16le.bin': 'utf-16le',
        'macintosh.bin': 'macintosh'
    };

    Object.keys(filesToEncoding).forEach(function(file) {
        fetchAndDecode(file, filesToEncoding[file]);
    });
    } else {
    document.querySelector('#results').textContent = 'Your browser does not support the Encoding API.'
    }

    // Use XHR to fetch `file` and interpret its contents as being encoded with `encoding`.
    function fetchAndDecode(file, encoding) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file);
    // Using 'arraybuffer' as the responseType ensures that the raw data is returned,
    // rather than letting XMLHttpRequest decode the data first.
    xhr.responseType = 'arraybuffer';
    xhr.onload = function() {
        if (this.status == 200) {
        // The decode() method takes a DataView as a parameter, which is a wrapper on top of the ArrayBuffer.
        var dataView = new DataView(this.response);
        // The TextDecoder interface is documented at http://encoding.spec.whatwg.org/#interface-textdecoder
        var decoder = new TextDecoder(encoding);
        var decodedString = decoder.decode(dataView);
        // Add the decoded file's text to the <pre> element on the page.
        document.querySelector('#results').textContent += decodedString + '\n';
        } else {
        console.error('Error while requesting', file, this);
        }
    };
    xhr.send();
    }
</script>

上記のサンプルでは、機能検出を使用して、必要な TextDecoder インターフェースが現在のブラウザで使用できるかどうかを判断し、使用できない場合はエラー メッセージを表示します。実際のアプリでは、ネイティブ サポートが利用できない場合は、別の実装にフォールバックするのが一般的です。幸いなことに、Renato が最初の記事で言及したテキスト エンコード ライブラリは今でも優れた選択肢です。このライブラリは、サポートしているブラウザでネイティブ メソッドを使用し、まだサポートを追加していないブラウザでは Encoding API のポリフィルを提供します。

2014 年 9 月更新: 現在のブラウザで Encoding API が使用できるかどうかを確認する方法を説明するようにサンプルを変更しました。