search
HomeWeb Front-endJS TutorialA closer look at Buffers in Node.js

A closer look at Buffers in Node.js

Jan 27, 2022 pm 06:27 PM
buffernode.jsbuffer

This article will give you an in-depth understanding of Buffer (buffer) in Node.js. It will introduce various ways to create the Buffer class, methods of writing to the buffer, etc. I hope it will be useful to everyone. Helped!

A closer look at Buffers in Node.js

#The JavaScript language itself only has string data types, not binary data types.

But when processing streams like TCP or file streams, binary data must be used. Therefore, in Node.js, a Buffer class is defined, which is used to create a buffer area specifically for storing binary data.

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 .

The original data is stored in an instance of the Buffer class.

A Buffer is similar to an integer array, but it corresponds to a piece of original memory outside the V8 heap memory.

Creating the Buffer class

The Node Buffer class can be created in a variety of ways.

Method 1

Create a Buffer instance with a length of 10 bytes:

var buf = new Buffer(10);

Method 2

Create a Buffer instance from the given array:

var buf = new Buffer([10, 20, 30, 40, 50]);

Method 3

Create a Buffer instance from a string:

var buf = new Buffer("bianchengsanmei", "utf-8");

utf-8 is the default encoding, and it also supports the following encodings: "ascii", "utf8", "utf16le", "ucs2", "base64" and "hex".

Write buffer

Syntax

The syntax for writing Node buffer is as follows:

buf.write(string[, offset[, length]][, encoding])

Parameters

The parameters are described as follows:

  • string - The string written to the buffer.
  • offset - The index value at which the buffer starts to be written, default is 0.
  • length - Number of bytes written, defaults to buffer.length
  • encoding - Encoding used. Defaults to 'utf8' .

Return value

Returns the actual written size. If there is insufficient buffer space, only part of the string will be written.
Example

buf = new Buffer(256);
len = buf.write("bi");
len = buf.write("bianchengsanmei"); 
console.log("写入字节数 : "+  len);

Execute the above code, the output result is:

$node main.js
写入字节数 : 15

Read data from the buffer

Syntax

The syntax for reading Node buffer data is as follows:

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

Parameters

The parameters are described as follows:

  • encoding - the encoding to use. Defaults to 'utf8' .

  • start - Specifies the index position to start reading, default is 0.

  • end - End position, defaults to the end of the buffer.

Return Value

Decode the buffer data and return a string using the specified encoding.

Example

buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
  buf[i] = i + 97;
}
 
console.log( buf.toString(&#39;ascii&#39;));       // 输出: abcdefghijklmnopqrstuvwxyz
console.log( buf.toString(&#39;ascii&#39;,0,5));   // 输出: abcde
console.log( buf.toString(&#39;utf8&#39;,0,5));    // 输出: abcde
console.log( buf.toString(undefined,0,5)); // 使用 &#39;utf8&#39; 编码, 并输出: abcde

Execute the above code, the output result is:

$ node main.js
abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde

Convert Buffer to JSON object

Syntax

The function syntax format for converting Node Buffer to JSON object is as follows:

buf.toJSON()

Return value

Returns JSON object.

Example

var buf = new Buffer(&#39;bianchengsanmei&#39;);
var json = buf.toJSON(buf);
 
console.log(json);

Execute the above code, the output result is:

{
  type: &#39;Buffer&#39;,
  data: [
     98, 105, 97, 110, 99, 104, 101, 110, 103, 115, 97, 110, 109, 101, 105
  ]
}

Buffer merge

Syntax

The syntax of Node buffer merging is as follows:

Buffer.concat(list[, totalLength])

Parameters

The parameters are described as follows:

  • list - an array list of Buffer objects used for merging.
  • totalLength - Specifies the total length of the combined Buffer objects.

Return value

Returns a new Buffer object that combines multiple members.

Example

var buffer1 = new Buffer(&#39;编程三昧 &#39;);
var buffer2 = new Buffer(&#39;bi&#39;);
var buffer2 = new Buffer(&#39;bianchengsanmei&#39;);
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3 内容: " + buffer3.toString());

Execute the above code, the output result is:

buffer3 内容: 编程三昧 bianchengsanmei

Buffer comparison

Syntax

The function syntax of Node Buffer comparison is as follows. This method was introduced in Node.js v0.12.2 version:

buf.compare(otherBuffer);

Parameters

Parameters The description is as follows:

  • otherBuffer - Another Buffer object compared with the buf object.

Return Value

Returns a number indicating that buf is before, after, or the same as otherBuffer.

Example

var buffer1 = new Buffer(&#39;ABC&#39;);
var buffer2 = new Buffer(&#39;ABCD&#39;);
var result = buffer1.compare(buffer2);
 
if(result < 0) {
   console.log(buffer1 + " 在 " + buffer2 + "之前");
}else if(result == 0){
   console.log(buffer1 + " 与 " + buffer2 + "相同");
}else {
   console.log(buffer1 + " 在 " + buffer2 + "之后");
}

Execute the above code, the output result is:

ABC在ABCD之前

Copy buffer

Syntax

Node buffer copy syntax is as follows:

buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])

Parameters

The parameters are described as follows:

  • targetBuffer - The Buffer object to be copied.
  • targetStart - number, optional, default: 0
  • sourceStart - number, optional, default: 0
  • sourceEnd - number, optional, default: buffer.length

Return value

No return value.

Example

var buffer1 = new Buffer(&#39;ABC&#39;);
// 拷贝一个缓冲区
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());

Execute the above code, the output result is:

buffer2 content: ABC

缓冲区裁剪

Node 缓冲区裁剪语法如下所示:

buf.slice([start[, end]])

参数

参数描述如下:

  • start - 数字, 可选, 默认: 0
  • end - 数字, 可选, 默认: buffer.length

返回值

返回一个新的缓冲区,它和旧缓冲区指向同一块内存,但是从索引 start 到 end 的位置剪切。

实例

var buffer1 = new Buffer(&#39;youj&#39;);
// 剪切缓冲区
var buffer2 = buffer1.slice(0,2);
console.log("buffer2 content: " + buffer2.toString());

执行以上代码,输出结果为:

buffer2 content: yo

缓冲区长度

语法 Node 缓冲区长度计算语法如下所示:

buf.length;

返回值

返回 Buffer 对象所占据的内存长度。

实例

var buffer = new Buffer(&#39;bianchengsanmei&#39;);
//  缓冲区长度
console.log("buffer length: " + buffer.length);

执行以上代码,输出结果为:

buffer length: 15

~

~本文完,感谢阅读!

更多node相关知识,请访问:nodejs 教程

The above is the detailed content of A closer look at Buffers in Node.js. 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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function