Conversão mais fácil de ArrayBuffer em string com a API Codificação

Há mais de dois anos, Renato Mangini descreveu um método de conversão entre ArrayBuffers brutos e a representação de string correspondente desses dados. No final da publicação, Renato mencionou que uma API padronizada oficial para lidar com a conversão estava em processo de elaboração. A especificação já foi aprimorada, e o Firefox e o Google Chrome adicionaram suporte nativo para as interfaces TextDecoder e TextEncoder.

Como demonstrado por este exemplo ativo, citado abaixo, a API Encoding simplifica a conversão entre bytes brutos e strings JavaScript nativas, independentemente de qual das muitas codificações padrão você precisa trabalhar.

<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>

O exemplo acima usa a detecção de recursos para determinar se a interface TextDecoder necessária está disponível no navegador atual e exibe uma mensagem de erro se não estiver. Em um aplicativo real, normalmente você usaria uma implementação alternativa se o suporte nativo não estivesse disponível. Felizmente, a biblioteca de codificação de texto que Renato mencionou no artigo original ainda é uma boa escolha. A biblioteca usa os métodos nativos em navegadores compatíveis e oferece polyfills para a API Encoding em navegadores que ainda não têm suporte.

Atualização, setembro de 2014: modificou o exemplo para ilustrar a verificação se a API Encoding está disponível no navegador atual.