兩年前,Renato Mangini 說明瞭在原始 ArrayBuffers 和該資料的對應字串表示法之間進行轉換的方法。文章的最後提到,Renato 提到正在進行轉換草稿的官方標準化 API,規格現已擴大,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
介面,如果沒有,就會顯示錯誤訊息。在實際的應用程式中,如果無法提供原生支援,您通常會想要改回其他實作方式。幸運的是,Renato 在原始文章中提到的文字編碼程式庫仍然是理想的選擇。這個程式庫會在支援這些方法的瀏覽器中使用原生方法,並在尚未支援這項功能的瀏覽器中為 Encoding API 提供 polyfill。
2014 年 9 月更新:修改範例,說明如何檢查目前的瀏覽器是否支援 Encoding API。