类 方法
| 方法 | 描述 |
|---|---|
| Buffer.isBuffer() | 判断是否Buffer对象 |
| Buffer.byteLength() | 计算指定字符串的字节数 |
| Buffer.concat() | 多个Buffer对象,组合成新的Buffer |
| Buffer.isEncoding() | 检测字符串是否为有效编码格式 |
创建缓冲区
//创建指定大小缓存区 var buf = Buffer.alloc(10); //创建指定大小缓存区,用 0 填充 var buf = Buffer.alloc(10, 0); //指定 数组 创建缓存区 var buf = Buffer.from(["a", "b", "c"]); //复制 Buffer 创建新的缓存区 var buf = Buffer.from(buf); //指定 字符串 创建缓存区 var buf = Buffer.from("liboke"); //指定 字符串 用指定 格式 创建缓存区 var buf = Buffer.from("liboke", "utf8"); //合并 多个Buffer 返回新的缓冲区 var buf = Buffer.concat([buf1, buf2], length); 参数: length 可选,指定新的缓冲区长度
编码转换
//中文写入缓存区要用 utf8 格式 var buf = Buffer.from("你好", "utf8"); console.log( buf ); //输出:<Buffer e4 bd a0 e5 a5 bd> console.log( buf.toString() ); //输出:你好 //转换为 base64 格式(中文不能直接转换) var b64 = buf.toString("base64"); //utf8 转 base64 console.log( b64 ); //输出:5L2g5aW9 console.log( Buffer.from(b64,"base64").toString() ); //输出:你好 //转换为 hex 格式(中文不能直接转换) var hex = buf.toString("hex"); //utf8 转 hex 十六进制 console.log( hex ); //输出:e4bda0e5a5bd console.log( Buffer.from(hex,"hex").toString() ); //输出:你好 //以字节编码 Buffer(中文不能直接转换) var latin1 = buf.toString("latin1"); //utf8 转 latin1 字符串 console.log( latin1 ); //输出:ä½ å¥½ console.log( Buffer.from(latin1,"latin1").toString() ); //输出:你好 注:ascii 格式,不能用于 中文 的转化,会丢掉高位字节
new 对象方法
| 方法 | 描述 |
|---|---|
| 写入 | |
| write() | 指定编码写入缓存区 |
| fill() | 指定值,填充缓存区指定位置 |
| 获取 | |
| length | 返回长度 |
| toString() | 指定编码返回字符串 |
| 比较 | |
| equals() | 比较两个缓冲区是否相等,相等true,不相等false |
| compare() | 比较内容大小 |
| 转换 | |
| toJSON() | 转化为JSON格式 的 数组 |
| JSON.stringify() | 转化为JSON格式 的 字符串 |
| JSON.parse() | 解析JSON格式 的 字符串(解析 JSON.stringify ) |
| 复制 | |
| copy() | 复制指定缓冲区,指定位置内容,替换指定缓冲区,指定位置 |
| slice() | 在缓冲区指定位置,创建新的指针 |
| 其它 | |
| writeIntLE() | |
| writeIntBE() | |
| readIntLE() | |
| readIntBE() | |
| writeUIntLE() | |
| writeUIntBE() | |
| readUIntLE() | |
| readUIntBE() | |
| writeInt8() | |
| writeUInt8() | |
| readInt8() | |
| readUInt8() | |
| writeInt16LE() | |
| writeInt16BE() | |
| writeUInt16LE() | |
| writeUInt16BE() | |
| readInt16LE() | |
| readInt16BE() | |
| readUInt16LE() | |
| readUInt16BE() | |
| writeInt32LE() | |
| writeInt32BE() | |
| writeUInt32LE() | |
| writeUInt32BE() | |
| readInt32LE() | |
| readInt32BE() | |
| readUInt32LE() | |
| readUInt32BE() | |
| writeFloatLE() | |
| writeFloatBE() | |
| readFloatLE() | |
| readFloatBE() | |
| writeDoubleLE() | |
| writeDoubleBE() | |
| readDoubleLE() | |
| readDoubleBE() | |