您的位置:首页 > 技术中心 > 前端框架 >

怎么将Nodejs中的buffer转为JSON格式和UTF-8字符串?

时间:2022-02-11 16:07

怎么将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)

// <Buffer 41 6c 6c 20 77 6f 72 6b 20 61 6e 64 20 6e 6f 20 70 6c 61 79 20 6d 61 6b 65 73 20 4a 61 63 6b 20 61 20 64 75 6c 6c 20 62 6f 79>

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 41 6c 6c 20 77 6f 72 6b 20 61 6e 64 20 6e 6f 20 70 6c 61 79 20 6d 61 6b 65 73 20 4a 61 63 6b 20 61 20 64 75 6c 6c 20 62 6f 79>

将 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 模块提供了用于将 Buffer 对象解码为字符串(以保留编码的多字节 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 实例被写入 StringDecoder 实例时,会使用内部的缓冲区来确保解码后的字符串不包含任何不完整的多字节字符。 这些都保存在缓冲区中,直到下一次调用 stringDecoder.write() 或调用 stringDecoder.end()

更多编程相关知识,请访问:编程视频!!

以上就是怎么将Nodejs中的buffer转为JSON格式和UTF-8字符串?的详细内容,更多请关注gxlsystem.com其它相关文章!

本类排行

今日推荐

热门手游