What is the Buffer.from() method in Node.js?
In Node.js, the Buffer.from() method creates a new buffer filled with the specified string, array, buffer, or arrayBuffer.
This method copies buffer data onto a new Buffer instance.
Syntax
Buffer.from(obj, encoding);
Parameters
-
obj: This is required. And it could be a string, array, or buffer. -
endcoding: This is optional. It is the encoding type. When not specified, Node.js usesutf8as default.
Return value
The Buffer.from() returns a buffer object.
Example
In this example, we will create a buffer using the Buffer.from(), access the buffer, and check the return value.
// Create a bufferlet buffer1 = Buffer.from("hello", "utf8")// log the buffer to the consoleconsole.log(buffer1);// Check the instance of bufferconsole.log(buffer1 instanceof Buffer)
In the example above, we created a buffer using a string. We logged it to the console. Then we checked the instance of the buffer to see whether it is actually an instance of the Buffer object, and whether it was true.