Buffer(缓冲器)和string_decoder(字符串解码器)

缓冲器是什么?储存字节的容器,buffer每个下标就是一个字节。

创建缓冲器:

let bf1 = Buffer.from("我是utf8字符串","utf8");   //用utf8解析字符串,变成字节,存进缓冲器

let bf2 = Buffer.from("e4bda0","hex");    //用16进制解析"16进制字符串",存进缓冲器

let bf3 = Buffer.from([0xe4,0xbd,0xa0]);   //另一个缓冲器存进缓冲器

let bf4 = Buffer.alloc(1024);    //创建容量为1024字节的缓冲器

缓冲器解码(string_decoder):

const { StringDecoder } = require('string_decoder');
let bf = Buffer.from("你","utf8");

let d1 = new StringDecoder('utf8');    //创建utf8解码器
let utf8Str = d1.write(bf);    //你   字节解码成utf8字符串

let d2 = new StringDecoder('hex');    //创建16进制解码器
let hexStr = d2.write(bf);    //e4bda0    字节解码成16进制字符串

缓冲器合并:

let bf1 = Buffer.from("abc");
let bf2 = Buffer.from("def");
let bf3 = Buffer.concat([bf1,bf2]);   //合并

console.log(bf3.toString());   //abcdef

缓冲器复制:

let bf1 = Buffer.from("abc");

let bf2 = Buffer.alloc(3);    
console.log(bf2);    //

bf1.copy(bf2,0,0,2);   //将bf1的数据复制到bf2
//说明:bf1.copy(bf2,从bf2的0索引开始覆盖,从bf1的0索引开始提取,从bf1的2索引结束提取); 不含2
console.log(bf2);    //
console.log(bf2.toString());    //ab

数据写入缓冲器:

let bf = Buffer.alloc(256);

bf.write("abcdefg",0,3,"utf8");   //数据写入缓冲器
//说明:bf.write("abcdefg",从缓冲器的0索引开始写入,写入3个字符,"编码格式");

console.log(bf.toString());   //abc

 

你可能感兴趣的:(node)