Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one is preferable: Buffer.from() or TextEncoder.encode()?

From my understanding and API docs, in Node the following are equivalent and return an Uint8Array:

Buffer.from(someString, 'utf-8')
(new TextEncoder()).encode(someString)

Is either of those on the way of becoming deprecated? Does someone know of any considerations that make either Buffer or TextEncoder/TextDecoder preferable over the other, if all that’s needed is converting UTF-8 strings to and from Uint8Arrays?

like image 596
Anton Strogonoff Avatar asked Jul 01 '26 15:07

Anton Strogonoff


1 Answers

From my understanding, Buffer is Node’s original implementation of binary blobs before equivalent feature has made its way into browser JS runtime.

After browsers went with a different API, Node runtime incorporated that as well (which makes sense from code portability standpoint), and preserved the original buffer support.

As a result, in Node there are multiple ways of achieving roughly similar results when it comes to binary blobs, where some ways will also work in browser while others won’t. Buffer.from()/TextEncoder.encode() might be one of them.

I’m not sure if there’s any performance gain to be had by choosing “Node classic” Buffer API over browser-compatible TextEncoder.

like image 78
Anton Strogonoff Avatar answered Jul 04 '26 04:07

Anton Strogonoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!