Home > Article > Web Front-end > Node.js practical code snippet to get the byte length of the Buffer object_node.js
We know that the Buffer object under the Node.js framework can provide good support for binary data, so obtaining the actual byte length of a Buffer object is a must-use function. The Node.js framework provides developers with a Buffer.byteLength() method . Below we use a routine provided by the official document to demonstrate the use of this method to readers.
The main code of ch04.buffer-byteLength.js in this example is as follows:
/** * ch04.buffer-byteLength.js */ console.info("------Buffer.byteLength()------"); console.info(); str = '\u00bd + \u00bc = \u00be'; //定义字符串 //½ + ¼ = ¾: 9 characters, 12 bytes console.log(str + ": " + str.length + " characters, " + Buffer.byteLength(str, 'utf8') + " bytes"); console.info(); console.info("------Buffer.byteLength()------");
【Code Analysis】
Line 06 of the code defines and initializes a string variable. The variable name is str, and the data content is u00bd + u00bc = u00be. Readers can go to relevant websites to check these hexadecimal codes. u00bd represents the character " ½", u00bc represents the character "¼", and u00be represents the character "¾"; then, in line 08 of the code, the length of the string variable str is displayed by printing the str.length property, and the characters are displayed through the Buffer.byteLength() method The actual byte length of the string variable str. The syntax of the Buffer.byteLength() method is as follows:
Syntax: Buffer.byteLength(string[, encoding])
This method returns a Number to represent the actual byte length of the string parameter. The encoding parameter defaults to "utf8" encoding format.
From the results shown in Figure 4.4, we can see that the length attribute of the string str is 9 characters long, and the occupied byte length is 12, so we can know "½", "¼" and "¾" These three characters actually occupy two bytes in length.
Tips: In this section we need to understand the similarities and differences between the two concepts of characters and bytes. In computer coding, one byte occupies 8 bits (1 byte = 8 bit) , and a character may be a single-byte character or a double-byte character. In addition, the Buffer.byteLength() method is often used when writing http response headers. If you want to rewrite the http response header Cotent-Length, be sure to use the Buffer.byteLength() method instead of String.prototype. length attribute.
The above is the first super practical Node.js code snippet shared with you. There are more exciting Node.js code snippets below. Don’t miss it. I hope it will be helpful to everyone’s learning.