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

1

14

How can I convert a string to a buffer?

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

Boggers answered 15/5, 2020 at 7:6 Comment(0)
A
15

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);
Awaken answered 15/5, 2020 at 7:7 Comment(2)
Thank you so much for the last part of using btoa and atob. You are a life saver!Hoenir
atob doesn't work with Japanese character setSudderth

© 2022 - 2024 — McMap. All rights reserved.