怎么将nodejs中的buffer转为json格式和utf-8字符串?下面本篇文章给大家介绍一下nodejs中buffer和json格式相互转换的方法,以及buffer 转换为 utf-8 字符串的方法。

Node.js 和基于浏览器的 JavaScript 有所不同,因为 Node 甚至在 ES6 草案提出 ArrayBuffer 之前就有处理二进制数据的方法。在 Node 中,Buffer(缓冲区) 类是大多数 I/O 操作使用的主要数据结构。它是在 V8 堆外部分配的原始二进制数据,一旦分配,就无法调整大小。【推荐学习:《nodejs 教程》】
在 Node v6.0 之前,要创建新的缓冲区,我们只需使用 new 关键字调用构造函数:
let newBuff = new Buffer('I Love You')v6.0 之后,要创建新的缓冲区实例:
let newBuff = Buffer.from('I Love You')new Buffer() 构造函数已被弃用,并被单独的 Buffer.from()、Buffer.alloc() 和 Buffer.allocUnsafe() 方法替换。
更多信息可以阅读官方文档。
将 Buffer 转换为 JSON
缓冲区可以转换为 JSON。
let bufferOne = Buffer.from('All work and no play makes Jack a dull boy')
console.log(bufferOne)
//
let json = JSON.stringify(bufferOne, null, 2)
console.log(json)
/*
{
"type": "Buffer",
"data": [
65,
108,
108,
32,
119,
111,
114,
107,
32,
97,
110,
100,
32,
110,
111,
32,
112,
108,
97,
121,
32,
109,
97,
107,
101,
115,
32,
74,
97,
99,
107,
32,
97,
32,
100,
117,
108,
108,
32,
98,
111,
121
]
}
*/ JSON 指定要转换的对象的类型是 Buffer 及其数据。
将 JSON 转换为 Buffer
let bufferOriginal = Buffer.from(JSON.parse(json).data) console.log(bufferOriginal) //
将 Buffer 转换为 UTF-8 字符串
console.log(bufferOriginal.toString('utf8')) // All work and no play makes Jack a dull boy.toString() 不是将缓冲区转换为字符串的唯一方法。此外,默认情况下,它会转换为 utf-8 格式字符串。
另一种将缓冲区转换为字符串的方法是使用 Node.js API 中的 StringDecoder 核心模块。
string_decoder 模块提供了用于将 string_decoder 对象解码为字符串(以保留编码的多字节 UTF-8 和 UTF-16 字符的方式)的 API。 上述例子的替代写法如下:
const { StringDecoder } = require('string_decoder')
const decoder = new StringDecoder('utf8')
let bufferOriginal = Buffer.from(JSON.parse(json).data)
console.log(decoder.write(bufferOriginal)) // All work and no play makes Jack a dull boy
console.log(decoder.end(bufferOriginal)) // All work and no play makes Jack a dull boy当 Buffer 实例被写入 Buffer 实例时,会使用内部的缓冲区来确保解码后的字符串不包含任何不完整的多字节字符。 这些都保存在缓冲区中,直到下一次调用 StringDecoder 或调用 stringDecoder.write()。
更多编程相关知识,请访问:编程视频!!










