تسهيل تحويل ArrayBuffer إلى سلسلة باستخدام واجهة برمجة التطبيقات Encode (واجهة برمجة التطبيقات)

قبل أكثر من عامَين، وصف Renato Mangini طريقة للتحويل بين ArrayBuffers الأولية وتمثيل السلسلة المقابل لتلك البيانات. في نهاية المشاركة، ذكر "ريناتو" أنّه جارٍ إعداد واجهة برمجة تطبيقات رسمية موحّدة لمعالجة الإحالة الناجحة. وقد أصبحت المواصفات جاهزة الآن، وأضاف كل من Firefox وGoogle 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 المطلوبة متاحة في المتصفح الحالي ويعرض رسالة خطأ إذا لم تكن متاحة. في التطبيق الحقيقي، قد تحتاج عادةً إلى الرجوع إلى عملية تنفيذ بديلة في حال عدم توفّر الدعم الأصلي. ولحسن الحظ، لا تزال مكتبة ترميز النص التي ذكرها "ريناتو" في مقالته الأصلية خيارًا جيدًا. تستخدم المكتبة الطرق الأصلية على المتصفحات التي تتوافق معها، وتعرض رموز polyfill API لترميز Encoding API على المتصفحات التي لا تتيح استخدام الترميز بعد.

تعديل، أيلول (سبتمبر) 2014: تم تعديل النموذج لتوضيح التحقق مما إذا كانت واجهة برمجة التطبيقات Encoding API متاحة في المتصفح الحالي.