Chuyển đổi ArrayBuffer sang String dễ dàng hơn nhờ Mã hoá API

Hơn hai năm trước, Renato Mangini đã mô tả một phương thức để chuyển đổi giữa ArrayBuffers thô và chuỗi đại diện tương ứng của dữ liệu đó. Ở cuối bài đăng, Renato đã đề cập rằng một API được chuẩn hoá chính thức để xử lý việc chuyển đổi đang trong quá trình soạn thảo. Thông số kỹ thuật hiện đã hoàn thiện, và cả FirefoxGoogle Chrome đều đã thêm dịch vụ hỗ trợ gốc cho giao diện TextDecoderTextEncoder.

Như được minh hoạ bằng mẫu trực tiếp này, được trích dẫn bên dưới, API mã hoá giúp bạn dễ dàng dịch giữa các byte thô và chuỗi JavaScript gốc, bất kể bạn cần phải sử dụng phương thức mã hoá chuẩn nào.

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

Mẫu ở trên sử dụng chức năng phát hiện tính năng để xác định xem giao diện TextDecoder bắt buộc có hoạt động trong trình duyệt hiện tại hay không và sẽ hiện thông báo lỗi nếu không có. Trong ứng dụng thực tế, thông thường, bạn sẽ muốn quay lại triển khai thay thế nếu không có sẵn dịch vụ hỗ trợ gốc. May mắn là thư viện mã hoá văn bản mà Renato đề cập trong bài viết gốc vẫn là lựa chọn tốt. Thư viện sử dụng các phương thức gốc trên các trình duyệt hỗ trợ các phương thức này và cung cấp các polyfill cho API Encoding trên các trình duyệt chưa hỗ trợ.

Cập nhật, tháng 9 năm 2014: Sửa đổi mẫu để minh họa việc kiểm tra xem API mã hóa có khả dụng trong trình duyệt hiện tại hay không.