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

How can I convert a string to a buffer?

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

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply