nodejs中的buffer

Buffer

  是Nodejs提供的可以直接操作二进制数据的类

从 Buffer 的定义Buffer继承自 Uint8Array

Uint8Array 则是8位无符号整型数组(一段以8bit数据为单位的无符号整型数组),是 ArrayBuffer 的一种

1.string 转 buffer

var buffer = Buffer.from("hello,world");
console.log(buffer);

<Buffer 68 65 6c 6c 6f 2c 77 6f 72 6c 64>

2.buffer 转字符串时,可以指定字符编码,默认值为 UTF-8 

var str = 'hello,world';
console.log(Buffer.from(str));
console.log(Buffer.from(str, 'utf8'));
console.log(Buffer.from(str, 'utf16le'));

<Buffer 68 65 6c 6c 6f 2c 77 6f 72 6c 64>
<Buffer 68 65 6c 6c 6f 2c 77 6f 72 6c 64>
<Buffer 68 00 65 00 6c 00 6c 00 6f 00 2c 00 77 00 6f 00 72 00 6c 00 64 00>

3.buffer t转 string

var buffer = Buffer.from("hello,world");
var ss = buffer.toString('utf8');
console.log(ss);

hello,world

4.buffer 转 base64

var buffer = Buffer.from("hello,world");
var base64 = buffer.toString('base64');
console.log(base64);

aGVsbG8sd29ybGQ=

5.buffer 转十六进制的字符

var buffer = Buffer.from('hello,world');
var hex = buffer.toString('hex');
console.log(buffer);
console.log(hex);

<Buffer 68 65 6c 6c 6f 2c 77 6f 72 6c 64>
68656c6c6f2c776f726c64

6.长度获取

var buffer = Buffer.from(('hello,world.'));
console.log(buffer.length);

12

6.多个buffer的合并

var buffer1 = Buffer.from(('hello,world.'));
var buffer2 = Buffer.from(('你好啊!'));
var buffer3 = Buffer.concat([buffer1, buffer2]);
console.log("buffer3内容: " + buffer3.toString());

buffer3内容: hello,world.你好啊!

7.将 Buffer 实例转换为 JSON 对象

var buffer = Buffer.from(("hello,world"));
console.log(buffer.toJSON());

{
  type: 'Buffer',
  data: [
    104, 101, 108, 108,
    111, 44, 119, 111,
    114, 108, 100
  ]
}

8.分割

var buffer = Buffer.from(("hello,world"));
console.log(buffer.slice(1,6).toString());

ello,

9.比较

返回一个数字,表示 buf 在 otherBuffer 之前,之后或相同

var buffer1 = Buffer.from('hello');
var buffer2 = Buffer.from('he');
var result = buffer1.compare(buffer2);
if (result < 0) {
     console.log(buffer1 + "" + buffer2 + "之前");
} else if (result == 0) {
     console.log(buffer1 + "" + buffer2 + "相同");
} else {
     console.log(buffer1 + "" + buffer2 + "之后");
}

hello 在 he之后

10.判断一个对象是否为一个Buffer

var buffer = Buffer.from("hello,world");
console.log(Buffer.isBuffer(buffer));
var ss = buffer.toString('utf8');
console.log(Buffer.isBuffer(ss));

true
false

posted @ 2020-11-13 22:50  慕尘  阅读(379)  评论(0编辑  收藏  举报