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

Use new blob read methods #457

Closed
jimmywarting opened this issue May 24, 2021 · 3 comments
Closed

Use new blob read methods #457

jimmywarting opened this issue May 24, 2021 · 3 comments

Comments

@jimmywarting
Copy link
Contributor

jimmywarting commented May 24, 2021

file-type/browser.js

Lines 23 to 45 in 7021d9a

function convertBlobToBuffer(blob) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.addEventListener('loadend', event => {
let data = event.target.result;
if (data instanceof ArrayBuffer) {
data = toBuffer(new Uint8Array(event.target.result));
}
resolve(data);
});
fileReader.addEventListener('error', event => {
reject(new Error(event.message));
});
fileReader.addEventListener('abort', event => {
reject(new Error(event.type));
});
fileReader.readAsArrayBuffer(blob);
});
}

To support Blob's in node v15.7 you need to start using the new blob read methods instead

- const toBuffer = require('typedarray-to-buffer');

async function fromBlob(blob) {
- const buffer = await convertBlobToBuffer(blob)
+ const buffer = await blob.arrayBuffer().then(Buffer.from)
  return core.fromBuffer(buffer)
}

- /**
- Convert Web API File to Node Buffer.
- @param {Blob} blob - Web API Blob.
- @returns {Promise<Buffer>}
- */
- function convertBlobToBuffer(blob) {
- 	return new Promise((resolve, reject) => {
- 		const fileReader = new FileReader();
- 		fileReader.addEventListener('loadend', event => {
- 			let data = event.target.result;
- 			if (data instanceof ArrayBuffer) {
- 				data = toBuffer(new Uint8Array(event.target.result));
- 			}
- 
- 			resolve(data);
- 		});
- 
- 		fileReader.addEventListener('error', event => {
- 			reject(new Error(event.message));
- 		});
- 
- 		fileReader.addEventListener('abort', event => {
- 			reject(new Error(event.type));
- 		});
- 
- 		fileReader.readAsArrayBuffer(blob);
- 	});
- }
@jimmywarting
Copy link
Contributor Author

You could also safely remove typedarray-to-buffer dep

@sindresorhus
Copy link
Owner

We can keep this open so we don't forget. We cannot do this until we target Node.js 16 though.

@sindresorhus sindresorhus reopened this May 24, 2021
@sindresorhus sindresorhus changed the title use new blob read methods Use new blob read methods May 24, 2021
@jimmywarting
Copy link
Contributor Author

jimmywarting commented May 24, 2021

I realised this was a dupe of my own #437

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