We know that the buffer object in the Node.js framework can provide good support for binary data, so it is necessary to get the real byte length of a buffer object. The Node.js Framework provides a Buffer.bytelength () method for developers, and the following is a routine example from an official document to show the reader how to use the method.
This example ch04.buffer-bytelength.js the main code as follows:
/**
* ch04.buffer-bytelength.js * *
console.info ("------buffer.bytelength ()------");
Console.info ();
str = ' \U00BD + \U00BC = \u00be '; Definition string
//½+¼=¾: 9 characters, bytes
console.log (str + ":" + str.length + "characters," + Buffer.bytel Ength (str, ' UTF8 ') + "bytes");
Console.info ();
Console.info ("------buffer.bytelength ()------");
"Code Analysis"
The No. 06 line of code defines and initializes a string variable named str with the data content of \U00BD + \U00BC = \u00be, the reader can go to the relevant website to look up these 16-encoded, \U00BD represent the character "½", \U00BC represent the character "¼", \ The u00be represents the character "¾", and then the No. 08 line of code displays the length of the string variable str by the PrintOut Str.length property, using the Buffer.bytelength () method to display the true byte length of the string variable str. A syntax description of the Buffer.bytelength () method is as follows:
Syntax: Buffer.bytelength (string[, encoding])
The method returns a number that represents the true byte length of the string parameter, and the encoding parameter defaults to the "UTF8" encoding format.
As you can see from the results shown in Figure 4.4, the length property of String str is 9 characters long and occupies 12 bytes, so we can know that the 3 characters "½", "¼" and "¾" actually occupy two bytes of length.
tip: In this section, we need to understand the similarities and differences between the two concepts of character and Byte, where one byte occupies 8 bit (1 byte = 8 bit) in the computer code, and one character may be a single-byte character, or it may be a double-byte character. In addition, the Buffer.bytelength () method is often used when writing HTTP response headers, and if you want to overwrite the HTTP response header Cotent-length, be sure to use the Buffer.bytelength () method instead of String.prototype.length property.
The above is for you to share the first Super Practical Node.js Code section, below there are more wonderful Node.js code section, don't miss, hope to help you learn.