Nodejs method to convert buffer into JSON object: 1. Use the "Buffer.from([data list])" statement to create a Buffer object; 2. Use the "JSON.stringify(Buffer object)" statement Convert.
The operating environment of this tutorial: windows7 system, nodejs version 12.19.0, DELL G3 computer.
In Node.js, the Buffer class is a core library released with the Node kernel. The Buffer library brings a method of storing raw data to Node.js, allowing Node.js to process binary data. Whenever you need to process data moved during I/O operations in Node.js, it is possible to use the Buffer library. . Raw data is stored in instances of the Buffer class. A Buffer is similar to an integer array, but it corresponds to a piece of raw memory outside of the V8 heap memory.
The official documentation recommends using the Buffer.from() interface to create a Buffer object.
The function syntax format for converting Node Buffer to JSON object is as follows:
buf.toJSON()
Will return: Return the JSON representation of buf.
When stringifying a Buffer instance, JSON.stringify() will implicitly call toJSON().
Example:
import { Buffer } from 'buffer'; const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); const json = JSON.stringify(buf); console.log(json); // 打印: {"type":"Buffer","data":[1,2,3,4,5]}
[Recommended learning: "nodejs tutorial"]
The above is the detailed content of How to convert buffer to JSON object in nodejs. For more information, please follow other related articles on the PHP Chinese website!