search
HomeWeb Front-endFront-end Q&ANode.js classic technique Buffer (summary sharing)

This article brings you relevant knowledge about Buffer in nodejs. In Node.js, the Buffer class is the core library released with the Node kernel. The Buffer library is brought to Node.js Here is a way to store raw data, I hope it will be helpful to everyone.

Node.js classic technique Buffer (summary sharing)

#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. Default is '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. Default is '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 <p>Execute the above code, the output result is: </p><pre class="brush:php;toolbar:false">$ 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('bianchengsanmei');
var json = buf.toJSON(buf);
 console.log(json);

Execute the above code, the output result is:

{ type: 'Buffer',
  data: [ 119, 119, 119, 46, 119, 51, 99, 115, 99, 104, 111, 111, 108, 46, 99, 110 ] }

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('编程三昧 ');
var buffer2 = new Buffer('bi');
var buffer2 = new Buffer('bianchengsanmei');
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('ABC');var buffer2 = new Buffer('ABCD');var result = buffer1.compare(buffer2);
 if(result <p>Execute the above code, the output result is: </p><pre class="brush:php;toolbar:false">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('ABC');
// 拷贝一个缓冲区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

Buffer clipping

Node buffer clipping syntax is as follows Shown:

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

Parameters

The parameters are described as follows:

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

返回值

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

实例

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

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

buffer2 content: yo

缓冲区长度

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

buf.length;

返回值

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

实例

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

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

buffer length: 15

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

The above is the detailed content of Node.js classic technique Buffer (summary sharing). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

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 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.