search
HomeWeb Front-endJS TutorialDetailed introduction to binary buffer objects in nodeJS

This article mainly introduces the binary bufferobject of nodeJS. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

Previous words

Before the introduction of TypedArray in ES6, the JavaScript language did not A mechanism for reading or manipulating binary data streams. The Buffer class was introduced as part of Nodejs' API, allowing it to handle binary data streams in scenarios such as TCP streams and file system operations. Now that TypedArray has been added to ES6, the Buffer class implements Uint8Array in a way that is better and more suitable for Node.js use cases. This article will introduce the buffer object in detail

Overview

Due to different application scenarios, in Node, the application needs to process network protocols, operate databases, and process Picture, receivinguploading files, etc. In the operation of network streams and files, a large amount of binary data must be processed. JavaScript's own string is far from meeting these needs. , so the Buffer object came into being

Buffer is a typical module that combines JavaScript and C++. It implements the performance-related parts in C++ and the non-performance-related parts in JavaScript. Instances of the Buffer class are similar to IntegersArrays, except that they are fixed-sized and physical memory is allocated outside the V8 heap. The size of the Buffer is determined when it is created and cannot be resized

Because Buffer is so common, Node has loaded it when the process starts and placed it on the global object (global). So when using Buffer, you can directly use

/*
{ [Function: Buffer]
 poolSize: 8192,
 from: [Function],
 alloc: [Function],
 allocUnsafe: [Function],
 allocUnsafeSlow: [Function],
 isBuffer: [Function: isBuffer],
 compare: [Function: compare],
 isEncoding: [Function],
 concat: [Function],
 byteLength: [Function: byteLength] }
 */
console.log(Buffer);

to create


before Node.js v6 without passing

require

() In the version, the Buffer instance is created through the Buffer constructor, which returns different Buffers according to the provided parameters, while the new version of nodejs provides corresponding methods

1,new Buffer(size). Pass a value as the first parameter to Buffer() (such as new Buffer(10)), then allocate a new Buffer object of the specified size

The memory allocated to this Buffer instance is uninitialized ( not padded with zeros). Although this design makes memory allocation very fast, the allocated memory segment may contain potentially sensitive old data

This Buffer instance must be initialized manually, using buf.fill(0) or writing Fill this Buffer. Although this behavior is intentional to improve performance, development experience shows that creating a fast but uninitialized Buffer is better than creating a slower but safer Buffer. There needs to be a clearer distinction between

var buf = new Buffer(5);
console.log(buf);//<Buffer e0 f7 1d 01 00>
buf.fill(0);
console.log(buf);//<Buffer 00 00 00 00 00>
[Note] When we allocate space for a Buffer object, its length is fixed and cannot be changed

var buf = new Buffer(5);
console.log(buf);//<Buffer b8 36 70 01 02>
buf[0] = 1;
console.log(buf);//<Buffer 01 36 70 01 02>
buf[10] = 1;
console.log(buf);//<Buffer 01 79 43 6f 6e>

[Buffer.allocUnsafe (size)】

In the new version, it is replaced by the Buffer.allocUnsafe(size) method to allocate a new Buffer of size bytes that is not filled with 0s. You can use buf.fill(0) to initialize the Buffer instance to 0

var buf = Buffer.allocUnsafe(10);
console.log(buf);//<Buffer 75 63 74 42 79 4c 65 6e 67 74>
buf.fill(0);
console.log(buf);//<Buffer 00 00 00 00 00 00 00 00 00 00>

[Buffer.alloc(size[, fill[, encoding]])】

In the new In this version, use the Buffer.alloc(size) method to generate a safe buffer object. The parameter size Integer

> the expected length of the new Buffer; fill String> ; | | The value used to prefill the newly created Buffer. Default: 0; encoding If fill is a string, this value is its character encoding. Default: 'utf8'Allocate a new Buffer of size bytes. If fill is undefined, the Buffer will be filled with 0

var buf = Buffer.alloc(5);
console.log(buf);//<Buffer 00 00 00 00 00>

2, new Buffer (array or buffer). If an array or Buffer is passed as the first parameter, the data of the passed object will be copied to the Buffer

var buf1 = new Buffer([1, 2, 3, 4, 5]);
console.log(buf1);//<Buffer 01 02 03 04 05>
var buf2 = new Buffer(buf1);
console.log(buf2);//<Buffer 01 02 03 04 05>

[Buffer.from(array or buffer)]

In the new version,

var buf1 = Buffer.from([1, 2, 3, 4, 5]);
console.log(buf1);//<Buffer 01 02 03 04 05>
var buf2 = Buffer.from(buf1);
console.log(buf2);//<Buffer 01 02 03 04 05>

3, new Buffer(string[, encoding]) is replaced by the Buffer.from(array or buffer) method. The first parameter is a string, and the second parameter is the encoding method. The default is 'utf-8'

var buf1 = new Buffer(&#39;this is a tést&#39;);
console.log(buf1.toString());//this is a tést
console.log(buf1.toString(&#39;ascii&#39;));//this is a tC)st
var buf2 = new Buffer(&#39;7468697320697320612074c3a97374&#39;, &#39;hex&#39;);
console.log(buf2.toString());//this is a tést

The character encodings currently supported by Node.js include:

&#39;ascii&#39; - 仅支持 7 位 ASCII 数据。如果设置去掉高位的话,这种编码是非常快的。
&#39;utf8&#39; - 多字节编码的 Unicode 字符。许多网页和其他文档格式都使用 UTF-8 。
&#39;utf16le&#39; - 2 或 4 个字节,小字节序编码的 Unicode 字符。支持代理对(U+10000 至 U+10FFFF)。
&#39;ucs2&#39; - &#39;utf16le&#39; 的别名。
&#39;base64&#39; - Base64 编码。当从字符串创建 Buffer 时,这种编码可接受“URL 与文件名安全字母表”。
&#39;latin1&#39; - 一种把 Buffer 编码成一字节编码的字符串的方式。
&#39;binary&#39; - &#39;latin1&#39; 的别名。
&#39;hex&#39; - 将每个字节编码为两个十六进制字符。

【Buffer.from(string[, encoding])】

在新版本中,由Buffer.from(string[, encoding]方法替代

var buf1 = Buffer.from(&#39;this is a tést&#39;);
console.log(buf1.toString());//this is a tést
console.log(buf1.toString(&#39;ascii&#39;));//this is a tC)st
var buf2 = Buffer.from(&#39;7468697320697320612074c3a97374&#39;, &#39;hex&#39;);
console.log(buf2.toString());//this is a tést

4、new Buffer(arrayBuffer[, byteOffset [, length]])。参数arrayBuffer 一个 ArrayBuffer,或一个 TypedArray 的 .buffer 属性;byteOffset 开始拷贝的索引。默认为 0;length 拷贝的字节数。默认为 arrayBuffer.length - byteOffset 

var arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
var buf = new Buffer(arr.buffer);
console.log(buf);//<Buffer 88 13 a0 0f>
arr[1] = 6000;
console.log(buf);//<Buffer 88 13 70 17>

【Buffer.from(arrayBuffer[, byteOffset [, length]])】

在新版本中,由Buffer.from(arrayBuffer[, byteOffset [, length]])方法替代

var arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
var buf = Buffer.from(arr.buffer);
console.log(buf);//<Buffer 88 13 a0 0f>
arr[1] = 6000;
console.log(buf);//<Buffer 88 13 70 17>

类数组

Buffer对象类似于数组,它的元素为16进制的两位数,即0到255的数值

console.log(Buffer.from(&#39;test&#39;));//<Buffer 74 65 73 74>

【长度】

不同编码的字符串占用的元素个数各不相同,中文字在UTF-8编码下占用3个元素,字母和半角标点符号占用1个元素

var buf = Buffer.from(&#39;match&#39;);
console.log(buf.length);//5
var buf = Buffer.from(&#39;火柴&#39;);
console.log(buf.length);//6

【下标】

Buffer受Array类型的影响很大,可以访问length属性得到长度,也可以通过下标访问元素

var buf = Buffer.alloc(10); 
console.log(buf.length); // => 10

上述代码分配了一个长10字节的Buffer对象。我们可以通过下标对它进行赋值

buf[0] = 100;
console.log(buf[0]); // => 100

要注意的是,给元素的赋值如果小于0,就将该值逐次加256,直到得到一个0到255之间的整数。如果得到的数值大于255,就逐次减256,直到得到0~255区间内的数值。如果是小数,舍弃小数部分,只保留整数部分 

buf[0] = -100;
console.log(buf[0]); // 156
buf[1] = 300;
console.log(buf[1]); // 44
buf[2] = 3.1415;
console.log(buf[2]); // 3

【fromcharcode】

通常地,创建的buffer对象的内容是其uft-8字符编码

var buf = Buffer.from(&#39;match&#39;); 
console.log(buf); //<Buffer 6d 61 74 63 68>

如果要访问其对应的字符,则需要使用字符串的fromCharCode()方法

console.log(String.fromCharCode(buf[0]));//&#39;m&#39;

内存分配

Buffer对象的内存分配不是在V8的堆内存中,而是在Node的C++层面实现内存的申请的。因为处理大量的字节数据不能采用需要一点内存就向操作系统申请一点内存的方式,这可能造成大量的内存申请的系统调用,对操作系统有一定压力。为此Node在内存的使用上应用的是在C++层面申请内存、在JavaScript中分配内存的策略

为了高效地使用申请来的内存,Node采用了slab分配机制。slab是一种动态内存管理机制,最早诞生于SunOS操作系统(Solaris)中,目前在一些*nix操作系统中有广泛的应用,如FreeBSD和Linux。简单而言,slab就是一块申请好的固定大小的内存区域。slab具有如下3种状态:full:完全分配状态;partial:部分分配状态;empty:没有被分配状态

当我们需要一个Buffer对象,可以通过以下方式分配指定大小的Buffer对象:

new Buffer(size);//旧
Buffer.alloc(size);//新

【poolSize】

poolSize属性是用于决定预分配的、内部 Buffer 实例池的大小的字节数。默认地,Node以8KB为界限来区分Buffer是大对象还是小对象:

Buffer.poolSize = 8 * 1024;

这个8KB的值也就是每个slab的大小值,在JavaScript层面,以它作为单位单元进行内存的分配

1、分配小Buffer对象

如果指定Buffer的大小少于8KB,Node会按照小对象的方式进行分配。Buffer的分配过程中主要使用一个局部变量pool作为中间处理对象,处于分配状态的slab单元都指向它。以下是分配一个全新的slab单元的操作,它会将新申请的SlowBuffer对象指向它:

var pool;
function allocPool() {
  pool = new SlowBuffer(Buffer.poolSize);
  pool.used = 0;
}

构造小Buffer对象时的代码如下:

new Buffer(1024);//旧
Buffer.alloc(1024);//新

这次构造将会去检查pool对象,如果pool没有被创建,将会创建一个新的slab单元指向它:

if (!pool || pool.length - pool.used < this.length) allocPool();

同时当前Buffer对象的parent属性指向该slab,并记录下是从这个slab的哪个位置(offset)开始使用的,slab对象自身也记录被使用了多少字节,代码如下:

this.parent = pool; 
this.offset = pool.used; 
pool.used += this.length;
if (pool.used & 7) pool.used = (pool.used + 8) & ~7;

这时候的slab状态为partial。当再次创建一个Buffer对象时,构造过程中将会判断这个slab的剩余空间是否足够。如果足够,使用剩余空间,并更新slab的分配状态。下面的代码创建了一个新的Buffer对象,它会引起一次slab分配:

new Buffer(3000);//旧
Buffer.alloc(3000);//新

如果slab剩余的空间不够,将会构造新的slab,原slab中剩余的空间会造成浪费。例如,第一次构造1字节的Buffer对象,第二次构造8192字节的Buffer对象,由于第二次分配时slab中的空间不够,所以创建并使用新的slab,第一个slab的8KB将会被第一个1字节的Buffer对象独占。下面的代码一共使用了两个slab单元:

new Buffer(1);//旧
Buffer.alloc(1);//新
new Buffer(8192);//旧
Buffer.alloc(8192);//新

要注意的是,由于同一个slab可能分配给多个Buffer对象使用,只有这些小Buffer对象在作用域释放并都可以回收时,slab的8KB空间才会被回收。尽管创建了1个字节的Buffer对象,但是如果不释放它,实际可能是8KB的内存没有释放

2、分配大Buffer对象

如果需要超过8KB的Buffer对象,将会直接分配一个SlowBuffer对象作为slab单元,这个slab单元将会被这个大Buffer对象独占

// Big buffer, just alloc one
this.parent = new SlowBuffer(this.length); 
this.offset = 0;

这里的SlowBuffer类是在C++中定义的,虽然引用buffer模块可以访问到它,但是不推荐直接操作它,而是用Buffer替代

上面提到的Buffer对象都是JavaScript层面的,能够被V8的垃圾回收标记回收。但是其内部的parent属性指向的SlowBuffer对象却来自于Node自身C++中的定义,是C++层面上的Buffer对象,所用内存不在V8的堆中

综上,真正的内存是在Node的C++层面提供的,JavaScript层面只是使用它。当进行小而频繁的Buffer操作时,采用slab的机制进行预先申请和事后分配,使得JavaScript到操作系统之间不必有过多的内存申请方面的系统调用。对于大块的Buffer而言,则直接使用C++层面提供的内存,而无需细腻的分配操作

 转换

Buffer对象可以与字符串之间相互转换。目前支持的字符串编码类型有如下几种:ASCII、UTF-8、UTF-16LE/UCS-2、Base64、Binary、Hex

【write()】

一个Buffer对象可以存储不同编码类型的字符串转码的值,调用write()方法可以实现该目的


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

  string 要写入 buf 的字符串

  offset 开始写入 string 的位置。默认: 0

  length 要写入的字节数。默认: buf.length - offset

  encoding string 的字符编码。默认: 'utf8';返回: 写入的字节数

根据 encoding 的字符编码写入 string 到 buf 中的 offset 位置。 length 参数是写入的字节数。 如果 buf 没有足够的空间保存整个字符串,则只会写入 string 的一部分。 只部分解码的字符不会被写入


var buf = Buffer.alloc(5); 
console.log(buf); //<Buffer 00 00 00 00 00>
var len = buf.write(&#39;test&#39;,1,3);
console.log(buf);//<Buffer 00 74 65 73 00>
console.log(len);/3

由于可以不断写入内容到Buffer对象中,并且每次写入可以指定编码,所以Buffer对象中可以存在多种编码转化后的内容。需要小心的是,每种编码所用的字节长度不同,将Buffer反转回字符串时需要谨慎处理

【toString()】

实现Buffer向字符串的转换也十分简单,Buffer对象的toString()可以将Buffer对象转换为字符串


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

  encoding - 使用的编码。默认为 'utf8'

  start - 指定开始读取的索引位置,默认为 0

  end - 结束位置,默认为缓冲区的末尾

  返回 - 解码缓冲区数据并使用指定的编码返回字符串 


var buf =Buffer.alloc(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));//abcde

【toJSON()】

将 Node Buffer 转换为 JSON 对象


buf.toJSON()

返回 buf 的 JSON 格式


var buf = Buffer.from(&#39;test&#39;);
var json = buf.toJSON(buf);
console.log(json);//{ type: &#39;Buffer&#39;, data: [ 116, 101, 115, 116 ] }

【isEncoding()】

目前比较遗憾的是,Node的Buffer对象支持的编码类型有限,只有少数的几种编码类型可以在字符串和Buffer之间转换。为此,Buffer提供了一个isEncoding()函数来判断编码是否支持转换


Buffer.isEncoding(encoding)

将编码类型作为参数传入上面的函数,如果支持转换返回值为true,否则为false。很遗憾的是,在中国常用的GBK、GB2312和BIG-5编码都不在支持的行列中


console.log(Buffer.isEncoding(&#39;utf8&#39;));//true
console.log(Buffer.isEncoding(&#39;gbk&#39;));//false

类方法

【Buffer.byteLength(string[, encoding])】

Buffer.byteLength()方法返回一个字符串的实际字节长度。 这与 String.prototype.length 不同,因为那返回字符串的字符数

string | | | | 要计算长度的值

encoding 如果 string 是字符串,则这是它的字符编码。 默认: 'utf8'

返回: string 包含的字节数


var str = &#39;火柴&#39;;
var buf = Buffer.from(str);
console.log(str.length);//2
console.log(buf.length);//6
console.log(buf.byteLength);//6

【Buffer.compare(buf1, buf2)】

该方法用于比较 buf1 和 buf2 ,通常用于 Buffer 实例数组的排序。 相当于调用 buf1.compare(buf2)

  buf1

  buf2

  Returns:


var buf1 = Buffer.from(&#39;1234&#39;);
var buf2 = Buffer.from(&#39;0123&#39;);
var arr = [buf1, buf2];
var result = Buffer.compare(buf1,buf2);
console.log(result);//1
console.log(arr.sort());//[ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]

【Buffer.concat(list[, totalLength])】

该方法返回一个合并了 list 中所有 Buffer 实例的新建的 Buffer

list 要合并的 Buffer 实例的数组

totalLength 合并时 list 中 Buffer 实例的总长度

返回:

如果 list 中没有元素、或 totalLength 为 0 ,则返回一个新建的长度为 0 的 Buffer 。如果没有提供 totalLength ,则从 list 中的 Buffer 实例计算得到。 为了计算 totalLength 会导致需要执行额外的循环,所以提供明确的长度会运行更快 


var buf1 = Buffer.alloc(10);
var buf2 = Buffer.alloc(14);
var buf3 = Buffer.alloc(18);
var totalLength = buf1.length + buf2.length + buf3.length;
console.log(totalLength);//42
var bufA = Buffer.concat([buf1, buf2, buf3], totalLength); 
console.log(bufA);//<Buffer 00 00 00 00 ...>
console.log(bufA.length);//42

【Buffer.isBuffer(obj)】

如果 obj 是一个 Buffer 则返回 true ,否则返回 false


var buf = Buffer.alloc(5);
var str = &#39;test&#39;;
console.log(Buffer.isBuffer(buf));//true
console.log(Buffer.isBuffer(str));//false

实例方法

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

  该方法返回一个指向相同原始内存的新建的 Buffer,但做了偏移且通过 start 和 end 索引进行裁剪

  start 新建的 Buffer 开始的位置。 默认: 0

  end 新建的 Buffer 结束的位置(不包含)。 默认: buf.length

  返回:


var buffer1 =Buffer.from(&#39;test&#39;);
console.log(buffer1);//<Buffer 74 65 73 74>
var buffer2 = buffer1.slice(1,3);
console.log(buffer2);//<Buffer 65 73>
console.log(buffer2.toString());//&#39;es&#39;

[注意]修改这个新建的 Buffer 切片,也会同时修改原始的 Buffer 的内存,因为这两个对象所分配的内存是重叠的


var buffer1 =Buffer.from(&#39;test&#39;);
console.log(buffer1);//<Buffer 74 65 73 74>
var buffer2 = buffer1.slice(1,3);
console.log(buffer2);//<Buffer 65 73>
buffer2[0] = 0;
console.log(buffer1);//<Buffer 74 00 73 74>
console.log(buffer2);//<Buffer 00 73>

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

  该方法用于拷贝 buf 的一个区域的数据到 target 的一个区域,即便 target 的内存区域与 buf 的重叠

  target | 要拷贝进的 Buffer 或 Uint8Array

  targetStart target 中开始拷贝进的偏移量。 默认: 0

  sourceStart buf 中开始拷贝的偏移量。 当 targetStart 为 undefined 时忽略。 默认: 0

  sourceEnd buf 中结束拷贝的偏移量(不包含)。 当 sourceStart 为 undefined 时忽略。 默认: buf.length

  返回: 被拷贝的字节数


var buffer1 =Buffer.from(&#39;test&#39;);
var buffer2 = Buffer.alloc(5);
var len = buffer1.copy(buffer2,1,3);
console.log(buffer1);//<Buffer 74 65 73 74>
console.log(buffer2);//<Buffer 00 74 00 00 00>
console.log(len);//1

【buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])】

  该方法比较 buf 与 target,返回表明 buf 在排序上是否排在 target 之前、或之后、或相同。 对比是基于各自 Buffer 实际的字节序列

  target 要比较的 Buffer

  targetStart target 中开始对比的偏移量。 默认: 0

  targetEnd target 中结束对比的偏移量(不包含)。 当 targetStart 为 undefined 时忽略。 默认: target.length

  sourceStart buf 中开始对比的偏移量。 当 targetStart 为 undefined 时忽略。 默认: 0

  sourceEnd buf 中结束对比的偏移量(不包含)。 当 targetStart 为 undefined 时忽略。 默认: buf.length

  返回:

  如果 target 与 buf 相同,则返回 0

  如果 target 排在 buf 前面,则返回 1

  如果 target 排在 buf 后面,则返回 -1 


var buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
var buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);

// 输出: 0(buf2中的1234对比buf2中的1234)
console.log(buf1.compare(buf2, 5, 9, 0, 4));

// 输出: -1(buf2中的567891对比buf1中的56789)
console.log(buf1.compare(buf2, 0, 6, 4));

// 输出: 1(buf2中的1对比buf2中的6789)
console.log(buf1.compare(buf2, 5, 6, 5));

【buf.equals(otherBuffer)】

  如果 buf 与 otherBuffer 具有完全相同的字节,则返回 true,否则返回 false

  otherBuffer 要比较的 Buffer

  返回:


var buf1 = Buffer.from(&#39;ABC&#39;);
var buf2 = Buffer.from(&#39;ABC&#39;);
var buf3 = Buffer.from(&#39;abc&#39;);
console.log(buf1.equals(buf2));//true
console.log(buf1.equals(buf3));//false

【buf.fill(value[, offset[, end]][, encoding])】

  value | | 用来填充 buf 的值

  offset 开始填充 buf 的位置。默认: 0

  end 结束填充 buf 的位置(不包含)。默认: buf.length

  encoding 如果 value 是一个字符串,则这是它的字符编码。 默认: 'utf8'

  返回: buf 的引用

  如果未指定 offset 和 end,则填充整个 buf。 这个简化使得一个Buffer的创建与填充可以在一行内完成


var b = Buffer.allocUnsafe(10).fill(&#39;h&#39;);
console.log(b.toString());//hhhhhhhhhh

【buf.indexOf(value[, byteOffset][, encoding])】

  value | | 搜索的值

  byteOffset buf 中开始搜索的位置。默认: 0

  encoding 如果 value 是一个字符串,则这是它的字符编码。 默认: 'utf8'

  返回: buf 中 value 首次出现的索引,如果 buf 没包含 value 则返回 -1

  如果value是字符串,则 value 根据 encoding 的字符编码进行解析;如果value是Buffer,则value会被作为一个整体使用。如果要比较部分 Buffer 可使用 buf.slice();如果value是数值,则 value 会解析为一个 0 至 255 之间的无符号八位整数值


var buf = Buffer.from(&#39;this is a buffer&#39;);

// 输出: 0
console.log(buf.indexOf(&#39;this&#39;));

// 输出: 2
console.log(buf.indexOf(&#39;is&#39;));

// 输出: 8
console.log(buf.indexOf(Buffer.from(&#39;a buffer&#39;)));

// 输出: 8
// (97 是 &#39;a&#39; 的十进制 ASCII 值)
console.log(buf.indexOf(97));

// 输出: -1
console.log(buf.indexOf(Buffer.from(&#39;a buffer example&#39;)));

// 输出: 8
console.log(buf.indexOf(Buffer.from(&#39;a buffer example&#39;).slice(0, 8)));

【buf.lastIndexOf(value[, byteOffset][, encoding])】

与 buf.indexOf() 类似,除了 buf 是从后往前搜索而不是从前往后


var buf = Buffer.from(&#39;this buffer is a buffer&#39;);

// 输出: 0
console.log(buf.lastIndexOf(&#39;this&#39;));

// 输出: 17
console.log(buf.lastIndexOf(&#39;buffer&#39;));

// 输出: 17
console.log(buf.lastIndexOf(Buffer.from(&#39;buffer&#39;)));

// 输出: 15
// (97 是 &#39;a&#39; 的十进制 ASCII 值)
console.log(buf.lastIndexOf(97));

// 输出: -1
console.log(buf.lastIndexOf(Buffer.from(&#39;yolo&#39;)));

// 输出: 5
console.log(buf.lastIndexOf(&#39;buffer&#39;, 5));

// 输出: -1
console.log(buf.lastIndexOf(&#39;buffer&#39;, 4));

【buf.includes(value[, byteOffset][, encoding])】

       该方法相当于 buf.indexOf() !== -1

  value | | 要搜索的值

  byteOffset buf 中开始搜索的位置。默认: 0

  encoding 如果 value 是一个字符串,则这是它的字符编码。 默认: 'utf8'

  返回: 如果 buf 找到 value,则返回 true,否则返回 false


var buf = Buffer.from(&#39;this is a buffer&#39;);

// 输出: true
console.log(buf.includes(&#39;this&#39;));

// 输出: true
console.log(buf.includes(&#39;is&#39;));

// 输出: true
console.log(buf.includes(Buffer.from(&#39;a buffer&#39;)));

// 输出: true
// (97 是 &#39;a&#39; 的十进制 ASCII 值)
console.log(buf.includes(97));

// 输出: false
console.log(buf.includes(Buffer.from(&#39;a buffer example&#39;)));

// 输出: true
console.log(buf.includes(Buffer.from(&#39;a buffer example&#39;).slice(0, 8)));

// 输出: false
console.log(buf.includes(&#39;this&#39;, 4));

The above is the detailed content of Detailed introduction to binary buffer objects in nodeJS. 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
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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)