How to useBuffer (Node.js Only) in Javascript

The Buffer class in Node.js can be used to convert a string into bytes by specifying the encoding type. This approach is particularly useful for server-side JavaScript running in a Node.js environment.

Example: In this example, we use the Buffer.from() method to convert a string into bytes using UTF-8 encoding. The Buffer object provides a toJSON() method to convert the buffer into an array of bytes, which can then be logged to the console.

JavaScript
const str1 = "Geeks";
const buffer = Buffer.from(str1, 'utf-8');
const result = Array.from(buffer);
console.log(result);


Output:

[ 71, 101, 101, 107, 115 ]




JavaScript Program to Convert String to Bytes

In this article, we are going to learn ho to Convert String to bytes in JavaScript. Converting a string to bytes in JavaScript involves encoding the characters using a specific character encoding (such as UTF-8) to represent the string as a sequence of bytes.

There are several methods that can be used to Convert String to bytes in JavaScript, which are listed below:

Table of Content

  • Approach 1: Using for Loop
  • Approach 2: Using Array.from() Method
  • Approach 3: Using TextEncoder API
  • Approach 4: Using Buffer (Node.js Only)


We will explore all the above methods along with their basic implementation with the help of examples.

Similar Reads

Approach 1: Using for Loop

In this approach, we are using for loop to iterate our given string characters and then converting each character to its Unicode points by using the charAt() method....

Approach 2: Using Array.from() Method

Using Array.from() to create an array from an iterable (like a string), with the provided mapping function converting each character to its Unicode code point....

Approach 3: Using TextEncoder API

In this approach,The TextEncoder API in JavaScript encodes a string into bytes, providing a byte representation using UTF-8 encoding,...

Approach 4: Using Buffer (Node.js Only)

The Buffer class in Node.js can be used to convert a string into bytes by specifying the encoding type. This approach is particularly useful for server-side JavaScript running in a Node.js environment....

Contact Us