Determining Buffer Length

A common task when dealing with buffers is determining the length, especially when you create a buffer dynamically from a string. You can determine the length of a buffer by calling .length on the Buffer object. To determine the byte length that a string will take up in a buffer, you cannot use the .length property. Instead, you need to use Buffer.byteLength(string, [encoding]). It is important to note that there is a difference between the string length and byte length of a buffer. To illustrate this, consider the following statements:

"UTF8 text u00b6".length;
//evaluates to 11
Buffer.byteLength("UTF8 text u00b6", 'utf8'),
//evaluates to 12
Buffer("UTF8 text u00b6").length;
//evaluates to 12

Notice that the same string evaluates to 11, but because it contains a double-byte character, the byteLength is 12. Also note that Buffer("UTF8 text u00b6").length evaluates to 12 also. This is because .length on a buffer returns the byte length.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset