sindresorhus/eslint-plugin-unicorn
Rule proposal: prefer TypedArray's over `node:buffer`
Closed
#1,808 opened on May 8, 2022
help wantednew rule
Repository metrics
- Stars
- (5,022 stars)
- PR merge metrics
- (Avg merge 1d 16h) (399 merged PRs in 30d)
Description
Description
This rule is more targeted for cross platform compatibility reasons. node:buffer is a node specific module and i mostly just see it as something that bloats browser bundles and runs slower (in none NodeJS contexts - or using npm:buffer instead of node:buffer).
TextEncoder/TextDecodercan be used instead to turn your buffer to / from string / Uint8Array and is also actually much faster thenBuffer.from(str)(which originally use string_decoder) in the browser,- DataView can be used instead of reading / writing bytes
- base64 & Hex string should be discouraged b/c it takes up more bandwidth and isn't well suited for json or large data, there are better ways to send things in binary format like with FormData or just uploading raw data, it also waste processing time to encode / decode data and strings in v8 strings are caped at 512 MiB now we have TypedArrays that are better
buffer.sliceis also overridinguint8array.slicewith subarray, which is also unexpected and now also deprecated- the buffer userland polyfill for the browser is also lagging behind
Buffer.isBuffercan be replaced withinstaceof Uint8Arrayto be acceptable of bothUint8Arrayandnode:buffer. something even better would be to accept any TypedArray usingArrayBuffer.isView- TextDecoder is also able to handle BOM - unlike
buf.toString() - NodeJS internal modules have also already been more acceptable of accepting any TypedArray, where as it only supported Buffer initially and wouldn't accept a Uint8Array.
I bet if you read this issue then you will maybe also be convinced that node:buffer is just unnecessary.
Fail
Buffer.from('hello world')
Pass
new TextEncoder().encode('hello world')
Additional Info
Replacing node:buffer with Uint8Array can be a lot. and maybe not that easy to autofix
Maybe dividing it up to smaller task could be easier.
like
- prefer
TextDecoderoverbuf.toString()andnode:string_encoder - prefer
instanceof Uint8ArrayoverBuffer.isBufferor something like that... - prefer DataView over read/write methods