Home > Web Front-end > JS Tutorial > body text

How to convert buffer to JSON object in nodejs

青灯夜游
Release: 2021-11-12 14:13:04
Original
5539 people have browsed it

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.

How to convert buffer to JSON object in nodejs

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()
Copy after login

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]}
Copy after login

[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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template