تبدیل ArrayBuffer به رشته آسان تر با Encoding API

بیش از دو سال پیش، Renato Mangini روشی را برای تبدیل بین ArrayBuffers خام و نمایش رشته متناظر آن داده توضیح داد. در پایان پست، رناتو اشاره کرد که یک API استاندارد رسمی برای مدیریت تبدیل در حال آماده‌سازی است. این مشخصات اکنون به بلوغ رسیده است و هر دو فایرفاکس و گوگل کروم پشتیبانی بومی را برای رابط های TextDecoder و TextEncoder اضافه کرده اند.

همانطور که در این نمونه زنده نشان داده شده است، API رمزگذاری ترجمه بین بایت های خام و رشته های جاوا اسکریپت بومی را ساده می کند، صرف نظر از اینکه با کدام یک از بسیاری از کدگذاری های استاندارد نیاز به کار دارید.

<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 مورد نیاز در مرورگر فعلی موجود است یا خیر، استفاده می‌کند و در صورت عدم وجود یک پیام خطا نمایش می‌دهد. در یک برنامه واقعی، اگر پشتیبانی بومی در دسترس نباشد، معمولاً می‌خواهید به یک پیاده‌سازی جایگزین بازگردید. خوشبختانه، کتابخانه رمزگذاری متنی که رناتو در مقاله اصلی خود به آن اشاره کرد، هنوز انتخاب خوبی است. این کتابخانه از روش‌های بومی در مرورگرهایی استفاده می‌کند که از آن‌ها پشتیبانی می‌کنند، و polyfills را برای Encoding API در مرورگرهایی که هنوز پشتیبانی اضافه نکرده‌اند، ارائه می‌دهد.

به‌روزرسانی، سپتامبر 2014 : نمونه را تغییر داد تا بررسی کند آیا API رمزگذاری در مرورگر فعلی موجود است یا خیر.