Challenge your understanding of how Node.js Buffer works with these easy-to-understand questions on basic concepts and examples.
Which method creates a new Buffer instance in Node.js with a specific size of 10 bytes?
Explanation: Buffer.alloc(10) creates a new buffer of 10 bytes. Buffer.make(10), Buffer.create(10), and Buffer.size(10) are not valid Buffer class methods in Node.js, so they would cause errors.
If you log a Buffer to the console, which data format is it typically displayed in by default?
Explanation: Node.js usually displays Buffer contents in hexadecimal format for readability. Decimal and binary are not the default formats, and base64 would require conversion.
Which method is used to convert buffer data to a string in Node.js?
Explanation: The toString() method is used to convert Buffer content to a string. stringify() and convert() are not Buffer methods, and toChar() does not exist in Buffer.
How do you create a Buffer from the string 'Hello'?
Explanation: Buffer.from('Hello') creates a buffer containing the UTF-8 bytes for 'Hello'. Buffer.alloc expects a size, Buffer.write is used to write into existing buffers, and Buffer.input does not exist.
Which method checks if a variable is a Buffer?
Explanation: Buffer.isBuffer(variable) returns true if the variable is a Buffer. The other method names are invalid and do not exist in the Buffer module.
What is the default character encoding used by Buffer when converting to or from a string?
Explanation: utf8 is the default encoding for Buffer in Node.js. ascii, base64, and hex are supported but not the default encoding.
Which property returns the number of bytes in a Buffer object?
Explanation: The length property gives the size of the Buffer in bytes. size, bytes, and count are not valid Buffer properties.
Which method writes a string into a Buffer?
Explanation: The write() method is used to store a string into a Buffer. insert(), append(), and put() are not Buffer methods in Node.js.
How would you access the first byte in a Buffer stored as variable buf?
Explanation: Buffer elements can be accessed using zero-based array indexing, like buf[0]. The other options are not valid ways to access Buffer bytes.
Which method copies data from one Buffer to another?
Explanation: The copy() method copies data from one Buffer to another. move(), clone(), and duplicate() are not Buffer methods in Node.js.