Buffer让js处理二进制
创建buffer
// 创建buffer
// 内存中锁定10个字节作为buffer空间
const b1 = Buffer.alloc(10)
// Buffer.from 可以接收一个字符串创建buffer
const b2 = Buffer.from('abc')
// Buffer.from 可以接收一个数组创建buffer
const b3 = Buffer.from(['ac','dd'])
// Buffer.from的第二个参数是编码方式
const b4 = Buffer.from('abc','utf8')
// Buffer.from 可以接收一个buffer创建buffer
const b5 = Buffer.from(b1)
buffer实例方法
const buf1 = Buffer.alloc(10)
// fill 填满buffer 填满为止, 如果内容不够就重复填充, 如果内容过多就截取部分填充
buf1.fill('123123465789')
console.log(buf1)
console.log(buf1.toString())
// write 写入
/**
* content 内容
* start 开始索引
* end 结束位置
*/
const buf2 = Buffer.alloc(10)
buf2.write('123',2,5)
console.log(buf2.toString())
// slice
/**
* start 开始
* end 结束
*/
const buf3 = Buffer.from('123456789')
const buf4 = buf3.slice()
console.log(buf4.toString())
const buf5 = buf3.slice(2,5)
console.log(buf5.toString())
// indexOf
/**
* target 目标
* start 开始位置
*/
const buf6 = Buffer.from('12345623456')
console.log(buf6.indexOf('2'))
console.log(buf6.indexOf('2',4))
// copy 用法 source.copy(target,start,len,end)
const buf7 = Buffer.alloc(6)
const buf8 = Buffer.from('杨洋')
buf8.copy(buf7,3,3,6)
console.log(buf7.toString())
Buffer静态方法
// Buffer.concat
// 接受一个元素为buffer实例的数组 返回一个新的buffer
const b1 = Buffer.from('are')
const b2 = Buffer.from('you')
const b3 = Buffer.from('ok')
let b = Buffer.concat([b1,b2,b3])
console.log(b.toString())
// Buffer.isBuffer
const b4 = Buffer.alloc(4)
console.log(Buffer.isBuffer(b4))