Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Browser's File Object (i.e. ArrayBuffers/Uint8Array) #292

Open
danielberndt opened this issue Feb 16, 2023 · 2 comments
Open

Comments

@danielberndt
Copy link

Hi there, I'm working in a browser-only context and would like to see if an uploaded file is a text file or not.
It seems though that the Buffer argument doesn't work with with the browser-based ArrayBuffer or Uint8Array (probably due to calling the buffer.toString with additional parameters). I could add a Buffer polyfill to my client code, but it would be nice if the native browser types would be supported as well.

@danielberndt
Copy link
Author

Just experimented with what needs to be done to use getEncoding with an Uint8Array instead of node's Buffer. And the only change I needed to make was this:

- const contentChunkUTF8 = buffer.toString(textEncoding, chunkBegin, chunkEnd)
+ const contentChunkUTF8 = new TextDecoder().decode(buffer.subarray(chunkBegin, chunkEnd));

Once that this change was made, a browser could read a file's content like this:

const handleChange = (e) => {
  const file = e.target.files[0];
  const reader = new FileReader();
  reader.onload = (e) => {
    console.log(getEncoding(new Uint8Array(e.target.result)));
  };
  reader.readAsArrayBuffer(file);
}

return <input type="file" onChange={handleChange}/>

I'm a bit hesitant to turn this into a PR as it's a fairly big architectural decision on how to support those two types in parallel.

@danielberndt danielberndt changed the title Support for Browser's File (i.e. ArrayBuffers) Support for Browser's File (i.e. ArrayBuffers/Uint8Array) Feb 16, 2023
@danielberndt danielberndt changed the title Support for Browser's File (i.e. ArrayBuffers/Uint8Array) Support for Browser's File Object (i.e. ArrayBuffers/Uint8Array) Feb 16, 2023
@balupton
Copy link
Member

balupton commented Jan 3, 2024

It seems TextDecoder is available in Node.js since Node.js v8: https://nodejs.org/api/util.html#class-utiltextdecoder

https://github.com/bevry/boundation does give us the ability to specify say a browser or worker entry, in case we need to load a different file for the package in that environment. Such is leveraged by: https://github.com/bevry/start-of-week/tree/master/source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants