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

readAsArrayBuffer returns Uint8Array instead of ArrayBuffer #2

Open
skratchdot opened this issue Mar 5, 2016 · 1 comment
Open

Comments

@skratchdot
Copy link

I have some browser code that does:

const reader = FileReader();
reader.addEventListener('load', (e) => {
  const arrayBuffer = e.target.result;
  const view = new DataView(arrayBuffer);
  // do some stuff with the view
});
reader.readAsArrayBuffer(file);

When I run my mocha tests in node (making node stubs using the node file-api package), I see the following error: TypeError: First argument to DataView constructor must be an ArrayBuffer

The fix for this is simple, but I don't know the ramifications for other people that use this library, so I don't know if you want me to submit a pull request or not. Anyways, the following 3 lines:

FileReader/FileReader.js

Lines 42 to 44 in 805a7b0

case 'buffer':
return data;
break;

Can be changed to:

case 'buffer':
  return toArrayBuffer(data);
  break;

And the following function needs to be included:

toArrayBuffer(buffer) {
  const ab = new ArrayBuffer(buffer.length);
  const view = new Uint8Array(ab);
  for (let i = 0; i < buffer.length; ++i) {
    view[i] = buffer[i];
  }
  return ab;
}
@skratchdot
Copy link
Author

In case anyone is reading, here's the patch I'm using in my tests:

    global.FileReader = function () {
      const reader = new FileReader();
      const originalAddEventListener = reader.addEventListener;
      reader.addEventListener = function (on, callback) {
        originalAddEventListener(on, (event) => {
          // convert Uint8Array to ArrayBuffer
          if (on === 'load' && event && event.target &&
            event.target.result && event.target.result.buffer) {
            event.target.result = toArrayBuffer(event.target.result.buffer);
          }
          callback(event);
        });
      };
      return reader;
    };

This is not a great monkey patch because it only works for people using readAsArrayBuffer() with a 'load' event listener...

@coolaj86 - Let me know if you want me to submit a PR. I have a workaround, so it's no big deal for me, but figured I'd log something in case anyone else has a similar issue...

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

1 participant