I managed to read the text file byte by byte and to change the charset from windows-1251 to Unicode for a file loaded from the end user's computer via an input
element and FileReader
. Now I want to do the same thing for a file from my server, via fetch
. Is it possible to do that? (The fetch
would be in a page served via HTTP and the URL would be relative, e.g. fetch("raw/graph_tab.txt")
— I'm not trying to read a file directly from the end user's machine as I was with an input
field and FileReader
).
Chunks of working code ('windows-1251.js' library is created by Mathias Bynens):
<input type="file" id="file"/>
<script type="text/javascript">
document.getElementById("file").addEventListener("change", readFile, false);
function readFile (evt) {
var files = evt.target.files;
var file = files[0];
var reader = new FileReader();
reader.onload = function(event) {
console.log(windows1251.decode(event.target.result));
}};
fetch() The global fetch() method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the Response object representing the response to your request.
XHR is an old way make requests to the server. Fetch API is a modern way to make requests to the server. Chaining is difficult in XHR, but in fetch you can easily chain the promises. In XHR we need to check the status property for the errors, but in fetch the catch method is there to handle errors.
The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.
more complicated API, request and response concepts are mixed together. lacks streaming, whole response is going to buffer in memory, not available for binary data.
If you mean you want to have the encoding
parameter of the FileReader.readAsText(Blob, encoding)
method, then you'd set a charset
parameter in the Content-Type
header of your response.
If this is not doable for whatever reason, then you'd have to consume your Response object to a Blob using its Body.blob() method, and then pass the resulting Blob to a FileReader.
Otherwise, no, even though the Response object has similar methods than the ones of a FileReader, the text()
method doesn't provide an encoding option...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With