Open In App
Related Articles

Node.js Buffer.from() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The Buffer.from() method is used to create a new buffer containing the specified string, array, or buffer. 

Syntax:

Buffer.from( object, encoding )

Parameters: This method accepts two parameters as mentioned above and described below:

  • object: This parameter can hold either a string, buffer, array, or array buffer.
  • encoding: If the object is a string then it is used to specify its encoding. It is an optional parameter. Its default value is utf8.

Example 1: In this example, we will see the use of the Buffer.from() method

javascript

// Node.js program to demonstrate the
// Buffer.from() Method
 
// Returns a new buffer with
// copy of the given string
const buf1 = Buffer.from("hello");
 
// Display the buffer object
// of the given string
console.log(buf1);
 
// Convert the buffer to the
// string and displays it
console.log(buf1.toString());

                    

Output:

<Buffer 68 65 6c 6c 6f>
hello

Example 2:  In this example, we will see the use of the Buffer.from() method

javascript

// Node.js program to demonstrate the
// Buffer.from() Method
 
// Creates an arrayBuffer with
// length 10
const arbuff = new ArrayBuffer(8);
 
// Returns a new buffer with a
// specified memory range within
// the arrayBuffer
const buf = Buffer.from(arbuff, 0, 2);
 
// Displays the length
console.log(buf.length);

                    

Output:

2

Example 3:  In this example, we will see the use of the Buffer.from() method

javascript

// Node.js program to demonstrate the
// Buffer.from() Method
 
// Create a new buffer with
// copy of the given string
const buf1 = Buffer.from("John");
 
// Create another buffer with
// copy of given buffer
const buf2 = Buffer.from(buf1);
 
// Display the buffer object
console.log(buf2);
 
// Convert the buffer to
// string and displays it
console.log(buf2.toString());

                    

Output:

<Buffer 4a 6f 68 6e>
John

Note: The above program will compile and run by using the node index.js command. 

Reference: https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_string_encoding



Last Updated : 11 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads