Learn more about Buffers in Node
At the end of the Stream chapter, we are left with a question, what is the chunk output by the following code?
Through printing, we find that chunk is a Buffer object, the elements of which are hexadecimal two-digit numbers, that is, values from 0 to 255. [Related tutorial recommendations: nodejs video tutorial, Programming teaching]
Explain that the data flowing in the Stream is the Buffer, then Let's explore the true face of Buffer!
? Why is Buffer introduced in Node?
At the beginning, JS only ran on the browser side. Unicode-encoded strings were easy to process, but for binary Difficulty handling strings with non-Unicode encodings. And binary is the lowest level data format of the computer. Video/audio/program/network packets are all stored in binary. So Node needs to introduce an object to operate binary, so Buffer was born, which is used for TCP stream/file system and other operations to process binary bytes.
Since Buffer is too commonly used in Node, Buffer has been introduced when Node starts, and there is no need to use require()
ArrayBuffer
What is it
ArrayBuffer is a piece of binary data in the memory. It cannot operate the memory itself. It needs to be operated through the TypedArray object or DataView. Represent the data in the buffer into a specific format, and read and write the contents of the buffer through these formats. It deploys an array interface and can use the array to operate data
TypedArray view
The most commonly used is the TypeArray view, which is used to read and write simple types of ArrayBuffer, such as Uint8Array (unsigned 8-bit integer) array view, Int16Array (16-bit integer) array view
Relationship with Buffer
The Buffer class in NodeJS is actually the implementation of Uint8Array.
Buffer structure
Buffer is an object similar to Array, but it is mainly used to operate bytes
Module structure
Buffer is a combination of JS and C The performance part of the module is implemented in C, and the non-performance part is implemented in JS.
The memory occupied by Buffer is not allocated by V8 and belongs to off-heap memory.
Object structure
The Buffer object is similar to an array, and its elements are two-digit hexadecimal digits, that is, values from 0 to 255
It can be seen from this example that different characters occupy different bytes in the Buffer. Under UTF-8 encoding, Chinese occupies 3 bytes, and English and half-width symbols occupy 1 byte.
? What will happen if the input element is a decimal/negative number/exceeds 255?
For the above situation, the processing of Buffer is:
- If the value assigned to the element is less than 0, the value will be assigned one by one Add 256 until you get an integer between 0 and 255
- If the value obtained is greater than 255, subtract 256 one by one until you get a value between 0 and 255
- If it is a decimal, Only the integer part is retained
Why does the Buffer display hexadecimal numbers
In fact, binary numbers are still stored in the memory, but the Buffer is displaying the memory The data uses a hexadecimal
buffer with a size of 2 bytes. There are 16 bits in total, such as 00000001 00100011
. If it is not convenient to display it directly like this, convert it to 16 bits. Base<buffer></buffer>
Creation of Buffer
Buffer.alloc and Buffer.allocUnsafe
Create fixed size buffer
Buffer.alloc(size [, fill [, encoding]])
- size The desired length of the new Buffer
- fill The value used to prefill the new Buffer. Default: 0
- encoding If fill is a string, this is its character encoding. Default value: utf8
Buffer.allocUnsafe(size)
Allocate a Buffer of size bytes, allocUnsafe executes faster than alloc , we found that the results are not initialized to 00 like Buffer.alloc
The memory segment allocated when allocUnsafe is called has not yet been initialized, so the memory allocation speed is very slow, but The allocated memory segment may contain old data. If these old data are not overwritten during use, memory leaks may occur. Although it is fast, try to avoid using it.
The Buffer module will pre-allocate an internal Buffer instance with a size of Buffer.poolSize as a quick allocation Memory pool, used to create new Buffer instances using allocUnsafe
Buffer.from
Create Buffer directly based on the content
- Buffer.from(string [, encoding] )
- Buffer.from(array)
- Buffer.from(buffer)
- full: Fully allocated state
- partial: Partially allocated state
- empty: No allocated status
Buffer The size is determined when created and cannot be adjusted!Allocate small objectsIf the allocated object is less than 8KB, Node will allocate it as a small objectThe Buffer allocation process mainly uses a The local variable pool serves as an intermediate processing object, and all slab units in the allocated state point to it. The following is the operation of allocating a brand new slab unit, which will point the newly applied SlowBuffer object to it
Node currently supports eight encoding methods: utf8, ucs2, utf16le, latin1, ascii, base64, hex, and base64Url. Specific implementation
For each different encoding scheme, a series of APIs will be implemented, and different results will be returned. Node.js will return different objects according to the incoming encoding
Buffer and string conversion
Convert string to Buffer
Mainly through the Buffer.from method mentioned above, the default encoding method is utf-8
Buffer to string
? Why are there garbled characters? How to solve this problem?
According to reading, the length of each read is 4, and the chunk output is as follows
For data = chunk
is equivalent to data = data.toString chunk.toString
Since one Chinese character occupies three bytes, the fourth byte in the first chunk will display garbled characters. , the first and second bytes of the second chunk cannot form text, etc., so the garbled problem will be displayed
For more node-related knowledge, please visit: nodejs tutorial!
The above is the detailed content of Learn more about Buffers in Node. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

With the development of Internet technology, front-end development has become increasingly important. Especially the popularity of mobile devices requires front-end development technology that is efficient, stable, safe and easy to maintain. As a rapidly developing programming language, Go language has been used by more and more developers. So, is it feasible to use Go language for front-end development? Next, this article will explain in detail how to use Go language for front-end development. Let’s first take a look at why Go language is used for front-end development. Many people think that Go language is a

As a C# developer, our development work usually includes front-end and back-end development. As technology develops and the complexity of projects increases, the collaborative development of front-end and back-end has become more and more important and complex. This article will share some front-end and back-end collaborative development techniques to help C# developers complete development work more efficiently. After determining the interface specifications, collaborative development of the front-end and back-end is inseparable from the interaction of API interfaces. To ensure the smooth progress of front-end and back-end collaborative development, the most important thing is to define good interface specifications. Interface specification involves the name of the interface

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Methods for implementing instant messaging include WebSocket, Long Polling, Server-Sent Events, WebRTC, etc. Detailed introduction: 1. WebSocket, which can establish a persistent connection between the client and the server to achieve real-time two-way communication. The front end can use the WebSocket API to create a WebSocket connection and achieve instant messaging by sending and receiving messages; 2. Long Polling, a technology that simulates real-time communication, etc.

Golang can be used as a front-end. Golang is a very versatile programming language that can be used to develop different types of applications, including front-end applications. By using Golang to write the front-end, you can get rid of a series of problems caused by languages such as JavaScript. For example, problems such as poor type safety, low performance, and difficult to maintain code.
