search
HomeWeb Front-endJS TutorialA brief analysis of Buffer in NodeJS

A brief analysis of Buffer in NodeJS

Nov 18, 2020 pm 05:59 PM
buffernodejs

A brief analysis of Buffer in NodeJS

Related recommendations: "node js tutorial"

I read Pu Ling's Nine Lights and One Deep NodeJS to get started with Node. , Park Dada’s book talks very little about practice and devotes more space to explaining principles. After listening to so many principles, he later started to use NodeJS in the field of front-end engineering but was hampered everywhere. Summarizing the reasons, he found that the difficult part in NodeJS is nothing more than files and files. Networking, file operations and networking all rely on a very important object - Stream, which is exactly what Park did not mention in his book.

Buffer Park Dada mentioned it in the book, but because the stream is actually processing the Buffer, it still needs to be briefly summarized.

What is Buffer

As introduced in the official API, before ES6 introduced TypedArray, JavaScript had no mechanism to read or operate binary data streams. The Buffer class was introduced as part of the NodeJS API to be able to interact with network streams such as TCP and file streams.

Now that TypedArray has been added to ES6, the Buffer class implements the Unit8Array API in a way that is more optimized and suitable for NodeJS operations.

In short, the Buffer class is used to process binary data. Because it is so commonly used, it is placed directly in a global variable, and there is no need to require when using it.

Instances of the Buffer class are similar to integer arrays, but the size of the buffer is determined when it is created and cannot be adjusted. The difference with the Buffer object is that it does not go through V8's memory allocation mechanism. Buffer is a module that combines JavaScript and C. The memory is applied for by C and allocated by JavaScript.

We will not discuss the related knowledge of Buffer memory allocation. Interested students can read Park Laoshi's book.

Instancing Buffer

Before NodeJS v6, Buffer was instantiated by calling the constructor, returning different results according to the parameters. For security reasons, this method has been abolished in versions after v6, and

  • Buffer.from()
  • Buffer.alloc()
  • ## is provided #Buffer.allocUnsafe()
Three separate functions with clear responsibilities handle the work of instantiating Buffer.

    Buffer.from(array): Returns a Buffer containing a copy of the provided byte. Each item in the array is a number representing an octet, so the value must be between 0 ~ between 255, otherwise it will be modulo
  • Buffer.from(arrayBuffer): Returns a new Buffer that shares memory with the given ArrayBuffer
  • Buffer.from(buffer): Returns the given Buffer A copy of Buffer
  • Buffer.from(string [, encoding]): Returns a Buffer containing the given string
  • Buffer.alloc(size [, fill [, encoding]]) : Returns a Buffer of the specified size and "filled"
  • Buffer.allocUnsafe(size): Returns a Buffer of the specified size, the content must be filled with methods such as buf.fill(0)
// 0x 表示 16 进制

Buffer.from([1, 2, 3]) // [0x1, 0x2, 0x3]

Buffer.from('test', 'utf-8') // [0x74, 0x65, 0x73, 0x74]

Buffer.alloc(5, 1) // [0x1, 0x1, 0x1, 0x1, 0x1]

Buffer.allocUnsafe(5); // 值不确定,后面详谈

Buffer.allocUnsafe() will execute faster than Buffer.alloc() It is unsafe to look at the name, and it is indeed unsafe.

When

Buffer.allocUnsafe() is called, the allocated memory segment has not been initialized (not returned to zero), so the memory allocation speed is very slow, but the allocated memory segment may contain old data. If you do not overwrite these old data when using it, it may cause memory leaks. Although it is fast, try to avoid using it.

Encoding

Buffer supports the following encoding formats

    ascii
  • utf8
  • utf16le
  • base64
  • binary
  • hex

Buffer and String conversion

String to Buffer is relatively simple

Buffer.from(string [, encoding])
At the same time, the Buffer instance also has a toString method to convert the Buffer into a string

buf.toString([encoding[, start[, end]]])

Buffer splicing

Use the concat method to speak multiple Buffer instances are spliced ​​into one Buffer instance

Buffer.concat(list[, totalLength])

StringDecoder

In NodeJS, a Chinese character is represented by three bytes. If we use something other than 3 when processing Chinese characters Multiples of the number of bytes will cause garbled character splicing problems.

const buf = Buffer.from('中文字符串!');

for(let i = 0; i You can see that there are garbled characters in the results<p></p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/024/535899bba38937963d5cf184db470e14-0.png?x-oss-process=image/resize,p_40" class="lazy" alt="" loading="lazy"></p>But if you use the string_decoder module, you can solve this problem<p></p><pre class="brush:php;toolbar:false">const StringDecoder = require('string_decoder').StringDecoder;
const decoder = new StringDecoder('utf8');

const buf = Buffer.from('中文字符串!');

for(let i = 0; i StringDecoder in After getting the encoding, we know that wide bytes occupy 3 bytes under UTF-8, so when processing the incomplete bytes at the end, they will be retained until the second write(). Currently only UTF-8, Base64 and UCS-2/UTF-16LE can be processed. <p></p><h2 id="buffer-其它常用-api">Buffer Other commonly used APIs<strong></strong>
</h2>There are also some Buffer commonly used APIs<p></p>
  • Buffer.isBuffer: Determine whether the object is a Buffer
  • Buffer.isEncoding: Determine the encoding of the Buffer object
  • buf.length: Return the bytes of memory requested for this Buffer instance The number is not the number of bytes of the Buffer instance content
  • buf.indexOf: Similar to the indexOf of the array, returns the position of a certain string, acsii code or buf in the modified buf
  • buf. copy: Copy (part of) the contents of one buf to another buf

For more programming-related knowledge, please visit:Programming Video! !

The above is the detailed content of A brief analysis of Buffer in NodeJS. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools