การแปลง ArrayBuffer ไปยังสตริงที่ง่ายขึ้นด้วย API การเข้ารหัส

ในช่วง 2 ปีที่ผ่านมา Renato Mangini ได้อธิบายเมธอดในการแปลงระหว่าง ArrayBuffers ดิบและการนำเสนอสตริงที่สอดคล้องกันของข้อมูลนั้น ในตอนท้ายของโพสต์ Renato ระบุว่า API มาตรฐานอย่างเป็นทางการสำหรับรองรับ Conversion อยู่ในกระบวนการร่าง ตอนนี้ข้อกำหนดมีการปรับปรุงอย่างสมบูรณ์แล้ว และทั้ง Firefox และ Google Chrome ก็ได้เพิ่มการรองรับในตัวสำหรับอินเทอร์เฟซ TextDecoder และ TextEncoder

จากตัวอย่างที่เผยแพร่อยู่นี้ที่ตัดตอนมาด้านล่าง Encrypting 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 ที่จำเป็นมีอยู่ในเบราว์เซอร์ปัจจุบันหรือไม่ และแสดงข้อความแสดงข้อผิดพลาดหากไม่พร้อมใช้งาน ในแอปพลิเคชันจริง ปกติแล้วคุณจะต้องการเลิกใช้ทางเลือกอื่นหากไม่มีการสนับสนุนแบบเนทีฟ โชคดีที่คลังการเข้ารหัสข้อความที่ Renato พูดถึงในบทความต้นฉบับของเขายังคงเป็นตัวเลือกที่ดี ไลบรารีนี้ใช้เมธอดแบบเนทีฟในเบราว์เซอร์ที่รองรับ และนำเสนอ Polyfills สำหรับ Encrypting API ในเบราว์เซอร์ที่ยังไม่ได้เพิ่มการสนับสนุน

อัปเดตเดือนกันยายน 2014: แก้ไขตัวอย่างเพื่อแสดงการตรวจสอบว่า Encrypting API พร้อมใช้งานในเบราว์เซอร์ปัจจุบันหรือไม่