13

How can I convert a string to a buffer?

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

Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
Juan Carlos
  • 318
  • 2
  • 9

1 Answers1

14

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);
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98