קל יותר מ-ArayBuffer להמרת מחרוזת באמצעות ממשק ה-API של הקידוד

לפני יותר משנתיים, רנאטו מנגיני תיאר שיטה להמרה בין ArrayBuffers לייצוג המחרוזת התואם של הנתונים האלה. בסוף הפוסט, רנאטו ציין שממשק API רשמי סטנדרטי לטיפול בהמרות נמצא בתהליך הכנה. המפרט הגיע לבשלות, והוספנו תמיכה מובנית בממשקים של TextDecoder ו-TextEncoder גם ב-Firefox וגם ב-Google Chrome.

כפי שמודגם בדוגמה הפעילה הזו, המצוטטת בהמשך, 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 הנדרש זמין בדפדפן הנוכחי, ומציגה הודעת שגיאה אם הממשק הזה לא זמין. אם אין תמיכה מובנית באפליקציה אמיתית, לרוב מומלץ להשתמש בהטמעה חלופית. למרבה המזל, ספריית קידוד הטקסט שרנאטו הזכיר במאמר המקורי שלו עדיין היא בחירה טובה. הספרייה משתמשת בשיטות המקוריות בדפדפנים שתומכים בהן, ומציעה מילויים עבור ממשק ה-API לקידוד בדפדפנים שעדיין לא תומכים בהם.

עדכון, ספטמבר 2014: בוצע שינוי בדוגמה כדי להמחיש אם ממשק ה-API לקידוד זמין בדפדפן הנוכחי.