Node.js Buffer.from() Method
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 stringvar buf1 = Buffer.from("hello"); // Display the buffer object// of the given stringconsole.log(buf1); // Convert the buffer to the // string and displays itconsole.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 10var arbuff = new ArrayBuffer(8); // Returns a new buffer with a// specified memory range within// the arrayBuffervar buf = Buffer.from(arbuff, 0, 2); // Displays the lengthconsole.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 stringvar buf1 = Buffer.from("John"); // Create another buffer with// copy of given buffervar buf2 = Buffer.from(buf1); // Display the buffer objectconsole.log(buf2); // Convert the buffer to// string and displays itconsole.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


