Conversione da Arraybuffer a stringa più semplice con l'API Codifica

Più di due anni fa, Renato Mangini ha descritto un metodo per la conversione tra ArrayBuffers non elaborati e la corrispondente rappresentazione stringa di quei dati. Alla fine del post, Renato affermava che era in corso la stesura di un'API standardizzata ufficiale per gestire la conversione. La specifica è ormai matura e sia Firefox che Google Chrome hanno aggiunto il supporto nativo per le interfacce TextDecoder e TextEncoder.

Come dimostrato da questo esempio in tempo reale, estratto di seguito, l'API di codifica semplifica la traduzione tra byte non elaborati e stringhe JavaScript native, indipendentemente dalle numerose codifiche standard con cui devi lavorare.

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

L'esempio riportato sopra utilizza il rilevamento delle funzionalità per determinare se l'interfaccia TextDecoder richiesta è disponibile nel browser corrente e mostra un messaggio di errore in caso contrario. In un'applicazione reale, in genere è consigliabile ricorrere a un'implementazione alternativa se il supporto nativo non è disponibile. Fortunatamente, la libreria di codifica del testo che Renato ha menzionato nel suo articolo originale è ancora una buona scelta. La libreria utilizza i metodi nativi sui browser che li supportano e offre il polyfill per l'API Encoding sui browser che non hanno ancora aggiunto supporto.

Aggiornamento, settembre 2014: è stato modificato l'esempio per illustrare il controllo della disponibilità dell'API Encoding nel browser corrente.