Home Web Front-end JS Tutorial How to use Buffer to encode and decode binary data in Node.js

How to use Buffer to encode and decode binary data in Node.js

Jun 30, 2018 pm 04:08 PM
buffer node.js

This article mainly introduces the detailed explanation of using Buffer to encode and decode binary data in Node.js. Buffer supports ascii, utf8, ucs2, base64 and other encoding formats. Friends in need can refer to it

JavaScript is very good at Handles strings, but because it was originally designed to handle HTML documents, it is not very good at handling binary data. JavaScript has no byte type, no structured types, not even byte arrays, only numbers and strings. (Original text: JavaScript doesn't have a byte type — it just has numbers — or structured types, or http://skylitecellars.com/ even byte arrays: It just has strings.)

Because Node is based on JavaScript , it can naturally handle text protocols like HTTP, but you can also use it to interact with databases, handle image or file uploads, etc. You can imagine how difficult it would be to do these things just using strings. Earlier, Node processed binary data by encoding bytes into text characters, but this approach later proved to be unfeasible, wasteful of resources, slow, inflexible, and difficult to maintain.

Node has a binary buffer implementation Buffer. This pseudo-class (pseudo-class) provides a series of APIs for processing binary data, simplifying tasks that require processing binary data. The length of the buffer is determined by the length of the byte data, and you can randomly set and get the byte data in the buffer.

Note: There is a special feature of the Buffer class. The memory occupied by the byte data in the buffer is not allocated on the JavaScrp

It VM memory heap, which means that these objects will not Processed by JavaScript's garbage collection algorithm, it is replaced by a permanent memory address that will not be modified, which also avoids CPU waste caused by memory copying of buffer contents.

Create a buffer

You can create a buffer using a UTF-8 string, like this:

var buf = new Buffer(‘Hello World!');
Copy after login

You can also use a string with a specified encoding Create buffer:

var buf = new Buffer('8b76fde713ce', 'base64');
Copy after login

Acceptable character encodings and identifiers are as follows:

1.ascii - ASCI, only applicable to the ASCII character set.
2.utf8 - UTF-8, this variable-width encoding is suitable for any character in the Unicode character set. It has become the preferred encoding in the Web world and is also the default encoding type of Node.
3.base64——Base64, this encoding is based on 64 printable ASCII characters to represent binary data. Base64 is usually used to embed binary data in character documents that can be converted into strings and can be complete when needed. Lossless conversion back to original binary format.

If there is no data to initialize the buffer, you can create an empty buffer with the specified capacity:

var buf = new Buffer(1024); // 创建一个1024字节的缓冲
Copy after login

Get and set buffer data

Create Or after receiving a buffer object, you may want to view or modify its content. You can access a certain byte of the buffer through the [] operator:

var buf = new Buffer('my buffer content');
// 访问缓冲内第10个字节
console.log(buf[10]); // -> 99
Copy after login

Note: When you (use the buffer capacity size) When creating an initialized buffer, be sure to note that the buffered data is not initialized to 0, but random data.

var buf = new Buffer(1024);
console.log(buf[100]); // -> 5 (某个随机值)
Copy after login

You can modify the data at any location in the buffer like this:

buf[99] = 125; // 把第100个字节的值设置为125
Copy after login

Note: In some cases, some buffer operations will not cause errors, such as:

1. The maximum value of bytes in the buffer is 255. If a byte is assigned a number greater than 256, it will be modulo 256, and then the result will be assigned to this byte.
2. If a certain byte in the buffer is assigned a value of 256, its actual value will be 0 (Translator's Note: Actually repeated with the first one, 256%6=0)
3. If you use A floating point number is assigned to a certain byte in the buffer, such as 100.7. The actual value will be the integer part of the floating point number - 100
4. If you try to assign a value to a location that exceeds the buffer capacity, the assignment operation will fail. The buffer is not modified in any way.

You can use the length attribute to get the length of the buffer:

var buf = new Buffer(100);
console.log(buf.length); // -> 100
Copy after login

You can also use the buffer length to iterate over the contents of the buffer to read or set each byte:

var buf = new Buffer(100);
for(var i = 0; i < buf.length; i++) {
    buf[i] = i;
}
Copy after login

The above code creates a new buffer containing 100 bytes and sets each byte in the buffer from 0 to 99.

Split buffer data

Once you create or receive a buffer, you may need to extract part of the buffer data. You can split the existing buffer data by specifying the starting position. buffer, thereby creating another smaller buffer:

var buffer = new Buffer("this is the content of my buffer");
var smallerBuffer = buffer.slice(8, 19);
console.log(smallerBuffer.toString()); // -> "the content"
Copy after login

Note that when splitting a buffer, no new memory is allocated or copied. The new buffer uses the memory of the parent buffer, which is just the parent buffer. Buffers a reference to a piece of data (specified by the starting position). This passage contains several meanings.

First of all, if your program modifies the contents of the parent buffer, these modifications will also affect the related child buffers. Because the parent buffer and the child buffer are different JavaScript objects, it is easy to ignore this problem and cause some Potential bugs.

Secondly, when you create a smaller child buffer from the parent buffer in this way, the parent buffer object will still be retained after the operation is completed and will not be garbage collected. If you don't pay attention, It is easy to cause memory leaks.

Note: If you are worried about memory leaks, you can use the copy method instead of the slice operation. Copy will be introduced below.

Copy buffer data

你可以像这样用copy将缓冲的一部分复制到另外一个缓冲:

var buffer1 = new Buffer("this is the content of my buffer");
var buffer2 = new Buffer(11);
var targetStart = 0;
var sourceStart = 8;
var sourceEnd = 19;
buffer1.copy(buffer2, targetStart, sourceStart, sourceEnd);
console.log(buffer2.toString()); // -> "the content"
Copy after login

上面代码,复制源缓冲的第9到20个字节到目标缓冲的开始位置。

解码缓冲数据

缓冲数据可以这样转换成一个UTF-8字符串:

var str = buf.toString();
Copy after login

还可以通过指定编码类型来将缓冲数据解码成任何编码类型的数据。比如,你想把一个缓冲解码成base64字符串,可以这么做:

var b64Str = buf.toString("base64");
Copy after login

使用toString函数,你还可以把一个UTF-8字符串转码成base64字符串:

var utf8String = &#39;my string&#39;;
var buf = new Buffer(utf8String);
var base64String = buf.toString(&#39;base64&#39;)
Copy after login

小结

有时候,你不得不跟二进制数据打交道,但是原生JavaScript又没有明确的方式来做这件事,于是Node提供了Buffer类,封装了一些针对连续内存块的操作。你可以在两个缓冲之间切分或复制内存数据。

你也可以把一个缓冲转换成某种编码的字符串,或者反过来,把一个字符串转化成缓冲,来访问或处理每个bit。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

nodejs中实现路由功能的方法

NodeJs基本语法和类型的介绍

深入解析node.js的exports、module.exports与ES6的export、export default

The above is the detailed content of How to use Buffer to encode and decode binary data in Node.js. For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

Node.js 19 is officially released, let's talk about its 6 major features! Node.js 19 is officially released, let's talk about its 6 major features! Nov 16, 2022 pm 08:34 PM

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Let's talk about the GC (garbage collection) mechanism in Node.js Let's talk about the GC (garbage collection) mechanism in Node.js Nov 29, 2022 pm 08:44 PM

How does Node.js do GC (garbage collection)? The following article will take you through it.

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

Learn more about Buffers in Node Learn more about Buffers in Node Apr 25, 2023 pm 07:49 PM

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package

See all articles