| 15 | |
| 16 | // Use XHR to fetch `file` and interpret its contents as being encoded with `encoding`. |
| 17 | function fetchAndDecode(file, encoding) { |
| 18 | var xhr = new XMLHttpRequest(); |
| 19 | xhr.open('GET', file); |
| 20 | // Using 'arraybuffer' as the responseType ensures that the raw data is returned, |
| 21 | // rather than letting XMLHttpRequest decode the data first. |
| 22 | xhr.responseType = 'arraybuffer'; |
| 23 | xhr.onload = function() { |
| 24 | if (this.status === 200) { |
| 25 | // The decode() method takes a DataView as a parameter, which is a wrapper on top of the ArrayBuffer. |
| 26 | var dataView = new DataView(this.response); |
| 27 | // The TextDecoder interface is documented at http://encoding.spec.whatwg.org/#interface-textdecoder |
| 28 | var decoder = new TextDecoder(encoding); |
| 29 | var decodedString = decoder.decode(dataView); |
| 30 | ChromeSamples.log(decodedString); |
| 31 | } else { |
| 32 | ChromeSamples.setStatus('Error while requesting', file, this.status); |
| 33 | } |
| 34 | }; |
| 35 | xhr.send(); |
| 36 | } |