Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's Deno equivalent of Node.js Buffer.from(string)

Tags:

node.js

deno

How can I convert a string to a buffer?

I tried: Uint8Array.from('hello world') but it isn't working

like image 700
Juan Carlos Avatar asked May 15 '20 07:05

Juan Carlos


People also ask

How do you convert a buffer to a string value in node JS?

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 is buffer type in node JS?

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.

Which method is used for writing to buffer in Node JS?

The write() method writes the specified string into a buffer, at the specified position.

Which method is used to read buffer in Node JS?

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.


1 Answers

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);
like image 85
Marcos Casagrande Avatar answered Nov 12 '22 04:11

Marcos Casagrande