This article describes how to get the Buffer object byte length from the Node. js practical code segment. For more information, see what we know under the Node. js framework.
Buffer objectIt can provide good support for binary data, so it is necessary to obtain the actual length of bytes of a Buffer object. The Node. js framework provides developers with
Buffer. byteLength () methodThe following describes how to use this method using the routine provided in an official document.
In this example, the main code of ch04.buffer-byteLength. js is as follows:
/*** Ch04.buffer-byteLength. js */console.info ("------ Buffer. byteLength () ------ "); console.info (); str = '\ u00bd + \ u00bc = \ u00be'; // defines the string // bytes + bytes = Bytes: 9 characters, 12 bytes console. log (str + ":" + str. length + "characters," + Buffer. byteLength (str, 'utf8') + "bytes"); console.info ("------ Buffer. byteLength ()------");
[Code analysis]
The Code in line 06th defines and initializes a string variable named str and the data content is \ u00bd + \ u00bc = \ u00be, for more information, see the hexadecimal codes on the relevant websites. u00bd stands for the character "bytes", u00bc stands for the character "bytes", and u00be stands for the character "bytes". Then, output str by printing the Code in line 2. length attribute to display the length of the string variable str, through Buffer. the byteLength () method is used to display the true byte length of the string variable str. the syntax of the byteLength () method is described as follows:
Syntax: Buffer. byteLength (string [, encoding])
This method returns a Number to indicate the actual bytes length of the string parameter. The default encoding parameter is in the UTF-8 encoding format.
From. the result displayed in 4 shows that the length attribute of the string str is 9 characters in length, while the occupied byte length is 12, therefore, we can know that the three characters "bytes", "bytes", and "bytes" actually occupy two bytes.
Tip:In this section, we need to understand the similarities and differences between the character and byte concepts. In computer coding, a byte occupies 8 bits (1 byte = 8 bits ), A character may be a single-byte character or double-byte character. In addition, Buffer. the byteLength () method is often used when writing http Response Headers. If you want to rewrite the http Response Header Cotent-Length, remember to use Buffer. byteLength () method instead of String. prototype. length attribute.
The above is the first ultra-practical Node. js code segment shared for everyone. There are more exciting Node. js code segments below. Don't miss them. I hope they will be helpful for everyone's learning.