sindresorhus/eslint-plugin-unicorn

Rule proposal: prefer TypedArray's over `node:buffer`

Closed

#1,808 opened on May 8, 2022

 (2 comments) (7 reactions) (0 assignees)JavaScript (468 forks)user submission
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 / TextDecoder can be used instead to turn your buffer to / from string / Uint8Array and is also actually much faster then Buffer.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.slice is also overriding uint8array.slice with subarray, which is also unexpected and now also deprecated
  • the buffer userland polyfill for the browser is also lagging behind
  • Buffer.isBuffer can be replaced with instaceof Uint8Array to be acceptable of both Uint8Array and node:buffer. something even better would be to accept any TypedArray using ArrayBuffer.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 TextDecoder over buf.toString() and node:string_encoder
  • prefer instanceof Uint8Array over Buffer.isBuffer or something like that...
  • prefer DataView over read/write methods

Contributor guide