简体   繁体   中英

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 Uint8Array s?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM