什么是Buffer?
Buffer
对象类似于数组,每一个元素都是 16
进制的两位数,即每一个元素可以表示一个 0-255
的值。
先看下Buffer
长啥样:
const buf = new Buffer('hello','utf-8')
console.log(buf); // <Buffer 68 65 6c 6c 6f>
判断是否为Buffer对象
Buffer
有个api
是Buffer.isBuffer()
,可以直接判断是否为buffer
对象
console.log(Buffer.isBuffer(buf)) // true
Buffer与JSON的互相转化
-
JSON
转为Buffer
const obj = { a: '1' };
const buf = new Buffer(`${JSON.stringify(obj)}`);
console.log(buf) // <Buffer 7b 22 61 22 3a 22 31 22 7d>
-
Buffer
转为JSON
先将Buffer
转化为string
,再转化为JSON
对象
const bufStr = buf.toString(); // 先将buf转化为string
const bufJson = JSON.parse(bufStr); // 再将string转化为json
console.log(bufJson) // { a: '1' }
网友评论