node里面的buffer理解

node提供了专门读写文件的模块,文件内容都是2进制存放在内存中的

node读取文件的结果都是16进制,那么你要学会进制转换,二进制0b开头 ,八进制0开头,十六进制0x

基础知识:

1字节=8bit

一个汉字=3字节,在不同的编码下字节个数还有不同的

一个英文=1字节

buffer里面用16机制表示

Buffer.alloc(3) // 3是代表字节

创建一个有3个字节的内存空间

<Buffer 00 00 00>

默认是0x00 0x00 0x00 0x00 

let buf1 = Buffer.alloc(12)
let buf2 = Buffer.from('hello')
let buf3 = Buffer.from('world')
buf2.copy(buf1, 0, 0, 5)
buf3.copy(buf1, 5, 0, 5)
console.log(buf1.toString())
// helloworld

简单的实现一下copy的方法

Buffer.prototype.copy = function (target, targetStart, sourceStart, sourceEnd) {
  for(let i = 0; i < sourceEnd-sourceStart; i++) {
    target[targetStart + i] = this[sourceStart + i]
  }
}

上面是通过copy方法把两个内存拷贝到一起,还有concat方法也可以

let cat = Buffer.concat([buf2, buf3])
两个buffer拼接到一起,返回的一个新的buffer,第二次参数是指定长度
 
基本原理是这样的
Buffer.concat = function (lists, len = lists.reduce((prev, next) => prev + next.length, 0)) {
  let buf = Buffer.alloc(len);
  let offset = 0;
  for(let i = 0; i < lists.length; i++) {
    lists[i].copy(buf, offset, 0, lists[i].length)
    offset += lists[i].length
  }
  return buf.slice(0, offset) // 返回有效的内容
}

buffet中的indexOf可以知道当前存在的位置

let index = Buffer.from('a*b').indexOf('*')
console.log(index)

当时很遗憾buffer没有split来拆分成两段buffer,辣么就自己写

Buffer.prototype.split = function (step) {
  let arr = [];
  let pos = 0;
  // 找不到返回-1
  let len = Buffer.from(step).length; // 按照buffer的长度来计算的呀
  let offset = 0; // 偏移量
  while (-1 !== (offset = this.indexOf(step, pos))) {
    arr.push(this.slice(pos, offset));
    pos = offset + len;
  }
  arr.push(this.slice(pos));
  return arr;
}

猜你喜欢

转载自www.cnblogs.com/wuxianqiang/p/10328296.html