Skip to content
Related Articles

Related Articles

Improve Article

Node.js | Buffer.from() Method

  • Last Updated : 30 Dec, 2019

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 accept two parameters as mentioned above and described below:

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

Example 1:




// Node.js program to demonstrate the  
// Buffer.from() Method
  
// Returns a new buffer with
// copy of the given string
var 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:




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

Output:

2

Example 3:




// Node.js program to demonstrate the  
// Buffer.from() Method
  
// Create a new buffer with
// copy of the given string
var buf1 = Buffer.from("John");
   
// Create another buffer with
// copy of given buffer
var 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




My Personal Notes arrow_drop_up
Recommended Articles
Page :