Kodlama API'si ile ArrayBuffer'dan Dizeye dönüştürme işlemi daha kolay

İki yılı aşkın bir süre önce Renato Mangini, ham ArrayBuffers ile bu verilerin karşılık gelen dize gösterimi arasında dönüşüm yapmak için bir yöntem açıkladı. Yazının sonunda Renato, bu dönüşümü gerçekleştirmek için kullanılan, standartlaştırılmış resmi bir API'nin taslak oluşturma sürecinde olduğunu belirtti. Spesifikasyon artık olgunlaşmış durumda. Hem Firefox hem de Google Chrome, TextDecoder ve TextEncoder arayüzleri için yerel destek ekledi.

Aşağıda alıntılanan bu canlı örnekte gösterildiği gibi Encoding API, hangi standart kodlamayla çalışmanız gerektiğinden bağımsız olarak ham baytlar ve yerel JavaScript dizeleri arasında çeviri yapmayı kolaylaştırır.

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

Yukarıdaki örnekte, gerekli TextDecoder arayüzünün mevcut tarayıcıda kullanılabilir olup olmadığını belirlemek için özellik algılama kullanılır. Kullanılabilir değilse bir hata mesajı gösterilir. Gerçek bir uygulamada, yerel destek mevcut değilse normalde alternatif bir uygulamayı tercih edersiniz. Neyse ki, Renato'nun orijinal makalesinde bahsettiği metin kodlama kitaplığı yine de iyi bir seçim. Kitaplık, destekleyen tarayıcılarda yerel yöntemleri kullanır ve henüz destek sunulmayan tarayıcılarda Kodlama API'si için çoklu dolgular sunar.

Güncelleme, Eylül 2014: Kodlama API'sinin mevcut tarayıcıda kullanılabilir olup olmadığını kontrol etmeyi göstermek için örnek değiştirildi.