How can I convert a string to a buffer?
I tried: Uint8Array.from('hello world')
but it isn't working
Buffers have a toString() method that you can use to convert the buffer to a string. By default, toString() converts the buffer to a string using UTF8 encoding. For example, if you create a buffer from a string using Buffer. from() , the toString() function gives you the original string back.
What Are Buffers? The Buffer class in Node. js is designed to handle raw binary data. Each buffer corresponds to some raw memory allocated outside V8. Buffers act somewhat like arrays of integers, but aren't resizable and have a whole bunch of methods specifically for binary data.
The write() method writes the specified string into a buffer, at the specified position.
The computer knows to process them differently because the bytes are encoded differently. Byte encoding is the format of the byte. A buffer in Node. js uses the UTF-8 encoding scheme by default if it's initialized with string data.
The equivalent of Buffer.from('Hello World')
is:
const encoder = new TextEncoder()
const buffer = encoder.encode('Hello World');
If you want to decode it back, you'll need to use TextDecoder
.
const decoder = new TextDecoder()
console.log(decoder.decode(buffer))
Deno tries to implement Web APIs when possible, reason why it works the same way on the browser.
const decoder = new TextDecoder();
const encoder = new TextEncoder();
const buffer = encoder.encode('Hello World');
console.log(buffer);
console.log(decoder.decode(buffer))
Have in mind that Node.js' Buffer
supports multiple encodings, such as base64
or hex
, which won't work with TextDecoder
So if you have a base64
string and want to convert it to utf8
instead of doing:
const base64String = Buffer.from('Hello World').toString('base64'); // Hello World
const utf8String = Buffer.from(base64String, 'base64').toString();
You would need to use atob
(Same as Web API) instead:
const base64String = btoa('Hello World');
const utf8String = atob(base64String);
console.log('Base64:', base64String);
console.log('utf8string:', utf8String);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With