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
const buf1 = Buffer.from( "hello" );
console.log(buf1);
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
const arbuff = new ArrayBuffer(8);
const buf = Buffer.from(arbuff, 0, 2);
console.log(buf.length);
|
Output:
2
Example 3: In this example, we will see the use of the Buffer.from() method
javascript
const buf1 = Buffer.from( "John" );
const buf2 = Buffer.from(buf1);
console.log(buf2);
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
11 Apr, 2023
Like Article
Save Article