Home > Web Front-end > JS Tutorial > body text

Node.js实用代码段之获取Buffer对象字节长度_node.js

WBOY
Release: 2016-05-16 15:10:26
Original
1568 people have browsed it

我们知道Node.js框架下的Buffer对象能够对二进制数据提供很好的支持,那么获取一个Buffer对象真实的字节长度则是必须要用到的功能了。Node.js框架为开发人员提供了一个Buffer.byteLength()方法,下面我们借助一个官方文档提供的例程向读者演示一下该方法的使用过程。

本例ch04.buffer-byteLength.js主要代码如下:

 /**
 * 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()------");  
Copy after login

【代码分析】

第06行代码定义并初始化了一个字符串变量,其变量名为str,数据内容为\u00bd + \u00bc = \u00be,读者可以去相关网站查阅一下这几个16进制编码,u00bd代表字符"½",u00bc代表字符"¼",u00be代表字符"¾";然后,在第08行代码通过打印输出str.length属性来显示字符串变量str的长度,通过Buffer.byteLength()方法来显示字符串变量str的真实字节长度,关于Buffer.byteLength()方法的语法说明如下:
语法:Buffer.byteLength(string[, encoding])
该方法返回一个Number数字,用来表示string参数的真实字节长度,encoding参数默认为"utf8"编码格式。

从图4.4中显示的结果可以看到,字符串str的length属性为9个字符长度,而占用字节长度为12 个,因此我们可以知道"½"、"¼"和"¾"这3个字符其实占用了两个字节的长度。

提示:本节我们需要了解字符与字节这两个概念的异同,在计算机编码中一个字节占用8 bit(1 byte = 8 bit),而一个字符可能是一个单字节字符,也可能是双字节字符。另外,Buffer.byteLength()方法在写http响应头时经常要用到,如果想改写http响应头Cotent-Length时,千万记得一定要用Buffer.byteLength()方法,而不要使用 String.prototype.length属性。

以上就是为大家分享的第一个超实用的Node.js代码段,下面还有更多精彩的Node.js代码段,不要错过,希望对大家的学习有所帮助。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!