search
HomeWeb Front-endJS TutorialDetailed explanation of some overlooked usage of Buffer in Node.js

Online articles about Buffer usage in Node.js There are many, but I feel they are still not detailed enough, so this article mainly introduces some usage of Buffer in Node.js that you may not know. The article introduces it in very detail. Friends who need it can refer to it. Let’s take a look together. .

##Preface

In most articles introducing Buffer, they mainly focus on the two aspects of data splicing and memory allocation. When using the fs module to

read the contents of a file, a Buffer is returned:

fs.readFile('filename', function (err, buf) {
 // <Buffer 2f 2a 2a 0a 20 2a 20 53 75 ... >
});

When using the net or http module to receive network data, the data

event The parameter is also a Buffer. At this time, we also need to use Buffer.concat() for data splicing:

var bufs = [];
conn.on(&#39;data&#39;, function (buf) {
 bufs.push(buf);
});
conn.on(&#39;end&#39;, function () {
 // 接收数据结束后,拼接所有收到的 Buffer 对象
 var buf = Buffer.concat(bufs);
});

can also use

Buffer.toString() Convert base64 or hexadecimal characters, such as:

console.log(new Buffer(&#39;hello, world!&#39;).toString(&#39;base64&#39;));
// 转换成 base64 字符串:aGVsbG8sIHdvcmxkIQ==

console.log(new Buffer(&#39;aGVsbG8sIHdvcmxkIQ==&#39;, &#39;base64&#39;).toString());
// 还原 base64 字符串:hello, world!

console.log(new Buffer(&#39;hello, world!&#39;).toString(&#39;hex&#39;));
// 转换成十六进制字符串:68656c6c6f2c20776f726c6421

console.log(new Buffer(&#39;68656c6c6f2c20776f726c6421&#39;, &#39;hex&#39;).toString());
// 还原十六进制字符串:hello, world!

Generally, a single Node.js process has a maximum memory limit. The following is an explanation from the official documentation:

What is the memory limit on a node process?

Currently, by default v8 has a memory limit of 512MB on 32-bit systems, and 1.4GB on 64-bit systems. The limit can be raised by setting --max_old_space_size to a maximum of ~1024 (~1 GB) (32-bit) and ~4096 (~4GB) (64-bit), but it is recommended that you split your single process into several workers if you are hitting memory limits.

Since the memory space occupied by the Buffer object is not counted in the memory space limit of the Node.js process, we often use Buffer to store data that requires a large amount of memory:

// 分配一个 2G-1 字节的数据
// 单次分配内存超过此值会抛出异常 RangeError: Invalid typed array length
var buf = new Buffer(1024 * 1024 * 1024 - 1);

The above are several common uses of Buffer. However, when reading the API documentation of Buffer, we will find more APIs starting with

readXXX() and writeXXX(), as follows:

  • buf.readUIntLE(offset, byteLength[, noAssert])

  • buf.readUIntBE(offset, byteLength[, noAssert])

  • buf.readIntLE(offset, byteLength[, noAssert])

  • buf.readIntBE(offset, byteLength[, noAssert])

  • buf.readUInt8(offset[, noAssert])

  • buf.readUInt16LE(offset[, noAssert])

  • buf.readUInt16BE(offset[ , noAssert])

  • buf.readUInt32LE(offset[, noAssert])

  • ##buf.readUInt32BE(offset[, noAssert])
  • buf.readInt8(offset[, noAssert])
  • buf.readInt16LE(offset[, noAssert])
  • buf.readInt16BE(offset[, noAssert])
  • buf.readInt32LE(offset[, noAssert])
  • buf. readInt32BE(offset[, noAssert])
  • buf.readFloatLE(offset[, noAssert])
  • ##buf.readFloatBE(offset[, noAssert ])
  • buf.readDoubleLE(offset[, noAssert])
  • ##buf.readDoubleBE(offset[, noAssert])

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

  • ##buf.writeUIntLE(value, offset, byteLength[, noAssert ])

  • buf.writeUIntBE(value, offset, byteLength[, noAssert])

  • buf.writeIntLE(value, offset, byteLength[ , noAssert])

  • buf.writeIntBE(value, offset, byteLength[, noAssert])

  • buf.writeUInt8(value, offset[ , noAssert])

  • buf.writeUInt16LE(value, offset[, noAssert])

  • ##buf.writeUInt16BE(value, offset[, noAssert ])
  • buf.writeUInt32LE(value, offset[, noAssert])
  • ##buf.writeUInt32BE(value, offset[, noAssert])
  • buf.writeInt8(value, offset[, noAssert])
  • buf.writeInt16LE(value, offset[, noAssert])
  • buf.writeInt16BE(value, offset[, noAssert])
  • buf.writeInt32LE(value, offset[, noAssert])
  • buf.writeInt32BE(value, offset[, noAssert])
  • buf.writeFloatLE(value, offset[, noAssert])
  • buf.writeFloatBE(value, offset[, noAssert])
  • ##buf.writeDoubleLE(value, offset[, noAssert])

  • buf.writeDoubleBE(value, offset[, noAssert])

  • These APIs provide great convenience for operating data in Node.js. Suppose we want to store an integer value into a file. For example, the current
  • timestamp
  • is 1447656645380. If it is stored as a string, it will take up 11 bytes of space and convert it to binary. Only 6 bytes of space are needed for storage:

    var buf = new Buffer(6);
    
    buf.writeUIntBE(1447656645380, 0, 6);
    // <Buffer 01 51 0f 0f 63 04>
    
    buf.readUIntBE(0, 6);
    // 1447656645380

    When using Node.js to write some low-level functions, such as a network communication module, a client module of a database, or need to operate a large number of files from a file When structuring data, the APIs provided by the above Buffer objects are essential.

  • The following will demonstrate an example of using the Buffer object to operate structured data.

操作结构化数据

假设有一个学生考试成绩数据库,每条记录结构如下:

学号 课程代码 分数
XXXXXX XXXX XX

其中学号是一个 6 位的数字,课程代码是一个 4 位数字,分数最高分为 100 分。

在使用文本来存储这些数据时,比如使用 CSV 格式存储可能是这样的:

100001,1001,99
100002,1001,67
100003,1001,88

其中每条记录占用 15 字节的空间,而使用二进制存储时其结构将会是这样:

学号 课程代码 分数
3 字节 2 字节 1 字节

每一条记录仅需要 6 字节的空间即可,仅仅是使用文本存储的 40%!下面是用来操作这些记录的程序:

// 读取一条记录
// buf Buffer 对象
// offset 本条记录在 Buffer 对象的开始位置
// data {number, lesson, score}
function writeRecord (buf, offset, data) {
 buf.writeUIntBE(data.number, offset, 3);
 buf.writeUInt16BE(data.lesson, offset + 3);
 buf.writeInt8(data.score, offset + 5);
}

// 写入一条记录
// buf Buffer 对象
// offset 本条记录在 Buffer 对象的开始位置
function readRecord (buf, offset) {
 return {
 number: buf.readUIntBE(offset, 3),
 lesson: buf.readUInt16BE(offset + 3),
 score: buf.readInt8(offset + 5)
 };
}

// 写入记录列表
// list 记录列表,每一条包含 {number, lesson, score}
function writeList (list) {
 var buf = new Buffer(list.length * 6);
 var offset = 0;
 for (var i = 0; i < list.length; i++) {
 writeRecord(buf, offset, list[i]);
 offset += 6;
 }
 return buf;
}

// 读取记录列表
// buf Buffer 对象
function readList (buf) {
 var offset = 0;
 var list = [];
 while (offset < buf.length) {
 list.push(readRecord(buf, offset));
 offset += 6;
 }
 return list;
}

我们可以再编写一段程序来看看效果:

var list = [
 {number: 100001, lesson: 1001, score: 99},
 {number: 100002, lesson: 1001, score: 88},
 {number: 100003, lesson: 1001, score: 77},
 {number: 100004, lesson: 1001, score: 66},
 {number: 100005, lesson: 1001, score: 55},
];
console.log(list);

var buf = writeList(list);
console.log(buf);
// 输出 <Buffer 01 86 a1 03 e9 63 01 86 a2 03 e9 58 01 86 a3 03 e9 4d 01 86 a4 03 e9 42 01 86 a5 03 e9 37>

var ret = readList(buf);
console.log(ret);
/* 输出
[ { number: 100001, lesson: 1001, score: 99 },
 { number: 100002, lesson: 1001, score: 88 },
 { number: 100003, lesson: 1001, score: 77 },
 { number: 100004, lesson: 1001, score: 66 },
 { number: 100005, lesson: 1001, score: 55 } ]
*/

lei-proto 模块介绍

上面的例子中,当每一条记录的结构有变化时,我们需要修改readRecord()writeRecord() ,重新计算每一个字段在 Buffer 中的偏移量,当记录的字段比较复杂时很容易出错。为此我编写了lei-proto模块,它允许你通过简单定义每条记录的结构即可生成对应的readRecord()`writeRecord()函数。

首先执行以下命令安装此模块:

$ npm install lei-proto --save

使用lei-proto模块后,前文的例子可以改为这样:

var parsePorto = require(&#39;lei-proto&#39;);

// 生成指定记录结构的数据编码/解码器
var record = parsePorto([
 [&#39;number&#39;, &#39;uint&#39;, 3],
 [&#39;lesson&#39;, &#39;uint&#39;, 2],
 [&#39;score&#39;, &#39;uint&#39;, 1]
]);

function readList (buf) {
 var list = [];
 var offset = 0;
 while (offset < buf.length) {
 list.push(record.decode(buf.slice(offset, offset + 6)));
 offset += 6;
 }
 return list;
}

function writeList (list) {
 return Buffer.concat(list.map(record.encodeEx));
}

运行与上文同样的测试程序,可看到其结果是一样的:

<Buffer 01 86 a1 03 e9 63 01 86 a2 03 e9 58 01 86 a3 03 e9 4d 01 86 a4 03 e9 42 01 86 a5 03 e9 37>
[ { number: 100001, lesson: 1001, score: 99 },
 { number: 100002, lesson: 1001, score: 88 },
 { number: 100003, lesson: 1001, score: 77 },
 { number: 100004, lesson: 1001, score: 66 },
 { number: 100005, lesson: 1001, score: 55 } ]

总结

The above is the detailed content of Detailed explanation of some overlooked usage of Buffer in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

怎么使用pkg将Node.js项目打包为可执行文件?怎么使用pkg将Node.js项目打包为可执行文件?Jul 26, 2022 pm 07:33 PM

如何用pkg打包nodejs可执行文件?下面本篇文章给大家介绍一下使用pkg将Node.js项目打包为可执行文件的方法,希望对大家有所帮助!

一文解析package.json和package-lock.json一文解析package.json和package-lock.jsonSep 01, 2022 pm 08:02 PM

本篇文章带大家详解package.json和package-lock.json文件,希望对大家有所帮助!

分享一个Nodejs web框架:Fastify分享一个Nodejs web框架:FastifyAug 04, 2022 pm 09:23 PM

本篇文章给大家分享一个Nodejs web框架:Fastify,简单介绍一下Fastify支持的特性、Fastify支持的插件以及Fastify的使用方法,希望对大家有所帮助!

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

手把手带你使用Node.js和adb开发一个手机备份小工具手把手带你使用Node.js和adb开发一个手机备份小工具Apr 14, 2022 pm 09:06 PM

本篇文章给大家分享一个Node实战,介绍一下使用Node.js和adb怎么开发一个手机备份小工具,希望对大家有所帮助!

图文详解node.js如何构建web服务器图文详解node.js如何构建web服务器Aug 08, 2022 am 10:27 AM

先介绍node.js的安装,再介绍使用node.js构建一个简单的web服务器,最后通过一个简单的示例,演示网页与服务器之间的数据交互的实现。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment