인코딩 API를 사용하여 ArrayBuffer를 문자열로 쉽게 변환

2년 전 Renato Mangini는 원시 ArrayBuffers 및 해당 데이터의 상응하는 문자열 표현 간에 변환하는 메서드를 설명했습니다. 게시물 말미에서 레나토는 전환을 처리하기 위한 공식 표준화된 API가 초안을 작성하는 과정에 있다고 언급했습니다. 이제 사양이 완성되어 FirefoxChrome에 모두 TextDecoderTextEncoder 인터페이스에 대한 기본 지원이 추가되었습니다.

아래 발췌된 이 라이브 샘플에서 볼 수 있듯이 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 인터페이스를 사용할 수 있는지 확인하고 사용할 수 없는 경우 오류 메시지를 표시합니다. 실제 애플리케이션에서는 기본 지원을 사용할 수 없는 경우 대체 구현으로 대체하는 것이 좋습니다. 다행히 레나토가 원래 기사에서 언급한 텍스트 인코딩 라이브러리는 여전히 좋은 선택입니다. 라이브러리는 네이티브 메서드를 지원하는 브라우저에서 네이티브 메서드를 사용하며, 아직 지원이 추가되지 않은 브라우저에서는 Encoding API용 폴리필을 제공합니다.

2014년 9월 업데이트: 현재 브라우저에서 인코딩 API를 사용할 수 있는지 확인하기 위해 샘플을 수정했습니다.