>  기사  >  웹 프론트엔드  >  Node.js의 Buffer 객체 작업(생성, 읽기 및 쓰기)에 대한 자세한 설명

Node.js의 Buffer 객체 작업(생성, 읽기 및 쓰기)에 대한 자세한 설명

青灯夜游
青灯夜游앞으로
2021-12-23 18:55:513497검색

이 글은 Node의 Buffer 객체를 안내하고 Buffer 객체를 생성하고 읽고 쓰는 방법을 소개합니다. 도움이 되길 바랍니다.

Node.js의 Buffer 객체 작업(생성, 읽기 및 쓰기)에 대한 자세한 설명

Buffer는 Node.js에 내장된 형식으로 바이너리 데이터를 저장하기 위해 메모리의 영역을 나타내는 데 사용됩니다.

버퍼는 사진, 동영상 등 바이너리 데이터를 나타내는 데 사용할 수 있습니다. 또한 파일에서 읽는 데이터도 버퍼 유형 데이터이고, 네트워크에서 수신하는 데이터도 버퍼 유형 데이터이므로 여전히 필요합니다. 버퍼를 배우다.

Buffer는 전역 범위에 있으므로 require('buffer')를 통해 Buffer를 도입할 필요가 없습니다. require('buffer') 来引入 Buffer。

创建 Buffer 对象

alloc

我们可以通过 Buffer.alloc(size, [fill], [encoding]) 来分配一个 size 字节大小的内存,还可以接收两个可选参数

  • fill:使用 fill 来填充 Buffer 中的每一个字节
  • encoding:如果 fill 为字符串,那么使用 encoding 来对字符串进行编码为二进制

当不指定 fill 参数,默认为填充 0。

const buf1 = Buffer.alloc(5);
console.log(buf1); // <Buffer 00 00 00 00 00>

const buf2 = Buffer.alloc(10, 1);
console.log(buf2); // <Buffer 01 01 01 01 01 01 01 01 01 01>

const buf3 = Buffer.alloc(12, "hello world!", "utf-8");
console.log(buf3); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64 21>

我们还可以使用 allocUnsafe(size) 来分配指定大小的内存,不过不会默认填充 0,其中的内容不确定

const buf = Buffer.allocUnsafe(5);
console.log(buf); // <Buffer c0 84 7c 2a 7b>

我们可以通过 fill(fill, encoding) 方法为 Buffer 对象填充指定值

const buf = Buffer.allocUnsafe(5);
buf.fill(0);
console.log(buf); // <Buffer 00 00 00 00 00>

from

我们也可以通过 Buffer.from() 方法来创建一个 Buffer 对象,from 方法可以接收的参数包括数组,字符串,Buffer 对象,对象等类型。

接收一个整形数组,数组中的整数应该在 0~255 之间,超出此范围的数字将会被截断

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

我们还可以像其中传入一个字符串,并指定编码,它会使用指定编码将字符串编码为二进制,如果不指定编码的话,默认为编码为 utf-8

const buf = Buffer.from("hello", "utf-8");
console.log(buf); // <Buffer 68 65 6c 6c 6f>

from 方法还可以接收一个 Buffer 对象,它会拷贝传入的 Buffer 对象中的数据到新的 Buffer 对象中

const buf1 = Buffer.from("hello", "utf-8");
const buf2 = Buffer.from(buf1);

console.log(buf1 === buf2); // false
console.log(buf2.toString()); // hello

from 方法还可以接收一个对象,当传入对象,首先会将对象转化为原始值,然后根据原始值转化为对应的二进制数组

let obj = {
  [Symbol.toPrimitive](hint) {
    return "a";
  },
};

const buf = Buffer.from(obj);
console.log(buf.toString()); // a

Buffer 对象的属性

length

通过 length 属性可以知道 Buffer 数组的长度

const buf = Buffer.from("Hello World!");

console.log(buf.length); // 12

buffer

Buffer 对象内部实际存储数据的是一个 ArrayBuffer 的对象,通过 buffer 属性可以得到这个对象

const buf = Buffer.alloc(5);

console.log(buf.buffer); // ArrayBuffer { [Uint8Contents]: <00 00 00 00 00>, byteLength: 5 }

读 Buffer 对象

本节介绍如何访问 Buffer 对象中的内容。

下标

在文章的开头提过,我们可以将 Buffer 对象看做是一个二进制数组,既然是数组,那么就可以通过下标的形式来访问数组中的内容。

const buf = Buffer.from([1, 2, 3, 4, 5]);
console.log(buf[0]); // 1
console.log(buf[5]); // undefined

它们会以补码的形式解析字节,返回对应的数字。

readXxx

我们还可以通过 buf.readInt8() buf.readInt16() buf.readUint8() buf.readUint16() 等方法来访问 Buffer 对象中的内容。

const buf = Buffer.from([1, 2, 3, 4, 5]);
console.log(buf.readInt8(2)); // 3

// 访问超出范围的内容,会抛出 RangeError
console.log(buf.readInt8(5)); // RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range.

迭代器

Buffer 对象的迭代器同数组的迭代器相同,也有三个迭代器,分别是

  • entries
  • keys
  • values

我们通过遍历迭代器来访问 Buffer 对象中的内容。

const buf = Buffer.from([3, 4, 2]);

for (let entry of buf.entries()) {
  // 数组的一个元素为下标,第二个元素为下标对应的元素
  console.log(entry); // [ 0, 3 ]
                      // [ 1, 4 ]
                      // [ 2, 2 ]
}
for (let key of buf.keys()) {
  console.log(key); // 0
                    // 1
                    // 2
}
for (let value of buf.values()) {
  console.log(value); // 3
                      // 4
                      // 2
}

写 Buffer 对象

本小节讲解如何向 Buffer 对象中写入内容。

下标

我们可以直接通过下标来改变 Buffer 对象中的内容

const buf = Buffer.from([1, 2, 3]);

// 通过下标设置值
buf[0] = 4;

console.log(buf); // <Buffer 04 02 03>

write

我们可以通过 write(string, [offset], [length], [encoding]) 方法向 Buffer 中写入字符串:

  • string:表示要写入的字符串
  • offset:偏移量,即跳过 offset 个字节开始写入,默认为 0
  • length:要写入的最大字节数,不超过 buf.length - offset,默认值为 buf.length - offset
  • encoding:指定编码,默认为 utf-8

该方法返回已写入的字节数。

const buf = Buffer.from([1, 2, 3, 4]);

// 跳过 1 个字节开始写入,1hi4
buf.write("hi", 1);

console.log(buf); // <Buffer 01 68 69 04>

writeXxx

同 readXxx,我们可以通过 writeInt8()

버퍼 객체 생성

alloc

Buffer.alloc(size, [fill], [encoding]) size 바이트 크기의 메모리를 할당하고 두 개의 선택적 매개변수를 받을 수도 있습니다🎜
  • fill : fill을 사용하여 버퍼의 모든 바이트를 채웁니다.
  • encoding: fill이 문자열인 경우 인코딩을 사용하여 문자열을 바이너리로 인코딩합니다.
🎜When fill 매개변수가 그렇지 않은 경우 지정하면 기본값은 0입니다. 🎜
const buf = Buffer.alloc(5);

buf.writeInt8(1, 0);
buf.writeInt8(3, 1);

console.log(buf); // <Buffer 01 03 00 00 00>
🎜allocUnsafe(size)를 사용하여 지정된 크기의 메모리를 할당할 수도 있지만 기본적으로 0으로 채워지지 않으며 내용이 불확실합니다.🎜
let obj1 = {};
let obj2 = Buffer.alloc(3);

console.log(Buffer.isBuffer(obj1)); // false
console.log(Buffer.isBuffer(obj2)); // true
🎜를 전달할 수 있습니다 >fill(fill, 인코딩) 메소드는 Buffer 객체를 지정된 값으로 채웁니다🎜
console.log(Buffer.isEncoding("utf-8")); // true
console.log(Buffer.isEncoding("utf8"));  // true
console.log(Buffer.isEncoding("hex"));   // true
console.log(Buffer.isEncoding("latin")); // false
console.log(Buffer.isEncoding("gbk"));   // false

from

🎜 Buffer.from () 메소드를 전달하여 Buffer 객체를 생성합니다. from 메소드는 배열, 문자열, Buffer 객체, 객체 및 기타 유형을 포함한 매개변수를 수신할 수 있습니다. 🎜🎜정수 배열을 받습니다. 배열의 정수는 0~255 사이여야 합니다. 이 범위를 벗어나는 숫자는 잘립니다.🎜
const buffer = Buffer.from("hello world!");

const newBuffer = buffer.slice(6); // 裁切 6 以后的内容到新数组
console.log(newBuffer.toString()); // world!

console.log(buffer.buffer === newBuffer.buffer); // true
🎜문자열을 전달하고 인코딩을 지정할 수도 있습니다. 지정된 인코딩을 사용하여 문자열을 바이너리로 인코딩합니다. 인코딩이 지정되지 않은 경우 기본 인코딩은 utf-8🎜
const buffer = Buffer.from("hello world!");

const newBuffer = buffer.subarray(6);
console.log(newBuffer.toString()); // world!

console.log(buffer.buffer === newBuffer.buffer); // true
🎜from입니다. 메서드도 버퍼 객체를 받을 수 있습니다. , 들어오는 Buffer 개체의 데이터를 새 Buffer 개체에 복사합니다🎜
const buf1 = Buffer.from("HelloWorld");
const buf2 = Buffer.alloc(8);

buf1.copy(buf2, 0, 1, 9);

console.log(buf2.toString()); // elloWorl
🎜from 메서드도 개체가 전달되면 개체가 먼저 원본으로 변환됩니다. 그런 다음 값은 원래 값을 기반으로 해당 이진 배열로 변환됩니다🎜
const buf = Buffer.from("HelloWorld");

// 默认从 0 开始搜索
console.log(buf.includes("H")); // true
// 从 1 开始搜索,后面不包含 H
console.log(buf.includes("H", 1)); // false

console.log(buf.includes(Buffer.from("Hello"))); // true

// H 对应的 utf-8 编码为 72
console.log(buf.includes(72)); // true

버퍼 개체의 속성

길이

🎜길이 속성을 통해 Buffer 배열의 길이를 알 수 있습니다🎜
const buf = Buffer.from("HelloWorld");

console.log(buf.indexOf("H")); // 0
console.log(buf.indexOf("H", 1)); // -1
console.log(buf.indexOf(Buffer.from("World"))); // 5
console.log(buf.indexOf(72)); // 0

buffer

🎜Buffer 개체의 실제 내부 콘텐츠 데이터는 ArrayBuffer 개체에 저장되며, 이는 버퍼 속성🎜
const buf1 = Buffer.alloc(5);
const buf2 = Buffer.alloc(5);
const buf3 = Buffer.allocUnsafe(5);

console.log(buf1.equals(buf2)); // true
console.log(buf1.equals(buf3)); // false

버퍼 개체 읽기

🎜를 통해 얻을 수 있습니다. 섹션에서는 Buffer 객체의 콘텐츠에 액세스하는 방법을 소개합니다. 🎜

Subscript

🎜글 시작 부분에서 언급했듯이 Buffer 객체는 바이너리 배열이므로 간주할 수 있습니다. array, 그런 다음 아래 첨자를 통해 배열의 내용에 액세스할 수 있습니다. 🎜rrreee🎜바이트를 보수 형식으로 구문 분석하고 해당 숫자를 반환합니다. 🎜

readXxx

🎜 buf.readInt8() buf.readInt16()을 전달할 수도 있습니다. buf.readUint8() buf.readUint16() 및 기타 메서드를 사용하여 Buffer 개체의 콘텐츠에 액세스합니다. 🎜rrreee

반복자

🎜 Buffer 객체의 반복자는 배열의 반복자와 동일합니다. 즉, 세 개의 반복자가 있습니다. 🎜
  • 항목
  • 🎜우리는 반복자를 순회하여 Buffer 개체의 콘텐츠에 액세스합니다. 🎜rrreeerrreeerrreee

    버퍼 개체 쓰기

    🎜이 섹션에서는 버퍼 개체에 콘텐츠를 쓰는 방법을 설명합니다. 🎜

    하위 첨자

    🎜하위 첨자를 통해 Buffer 객체의 내용을 직접 변경할 수 있습니다🎜rrreee

    write

    🎜 write(string, [offset], [length], [encoding]) 메서드를 통해 Buffer에 문자를 쓸 수 있습니다. 🎜
    • string: 쓸 문자열을 나타냅니다.
    • offset: offset, 즉 쓰기 시작을 위해 오프셋 바이트를 건너뛰고, 기본값은 0입니다.
    • length: The 기록할 최대 바이트 수, buf.length - offset 이하, 기본값은 buf.length - offset
    • 인코딩: 지정 인코딩, 기본값은 utf-8
    🎜이 메서드는 작성된 바이트 수를 반환합니다. 🎜rrreee

    writeXxx

    🎜readXxx와 동일하며 writeInt8() 메서드를 통해 buf에 데이터를 쓸 수 있습니다. , 메소드는 두 개의 매개변수를 받습니다: 🎜
    • value:要写入的值
    • offset:偏移量,默认为 0
    const buf = Buffer.alloc(5);
    
    buf.writeInt8(1, 0);
    buf.writeInt8(3, 1);
    
    console.log(buf); // <Buffer 01 03 00 00 00>

    踩坑:没有 writeInt16(),不过有 writeInt16BE()writeInt16LE(),分别代表以大端序、小端序写入。

    其他方法

    isBuffer

    该方法接收一个对象,用来判断该对象是不是一个 Buffer 对象

    let obj1 = {};
    let obj2 = Buffer.alloc(3);
    
    console.log(Buffer.isBuffer(obj1)); // false
    console.log(Buffer.isBuffer(obj2)); // true

    isEncoding

    该方法接收一个代表编码的字符串,返回 Buffer 是否支持该种编码,如果支持则返回 true,否则返回 false

    console.log(Buffer.isEncoding("utf-8")); // true
    console.log(Buffer.isEncoding("utf8"));  // true
    console.log(Buffer.isEncoding("hex"));   // true
    console.log(Buffer.isEncoding("latin")); // false
    console.log(Buffer.isEncoding("gbk"));   // false

    slice

    slice(start, end) 可以裁切原有的 Buffer 对象,返回一个新的 Buffer 对象,其中 start 和 end 代表裁切的起始位置和结束位置,左闭右开 [start, end),这两个参数是可选的,start 默认为 0,end 默认为 buf.length。返回的 Buffer 对象与原先对象引用的是同一块内存,即它们的 buffer 属性是一样的。

    const buffer = Buffer.from("hello world!");
    
    const newBuffer = buffer.slice(6); // 裁切 6 以后的内容到新数组
    console.log(newBuffer.toString()); // world!
    
    console.log(buffer.buffer === newBuffer.buffer); // true

    subarray

    subarray(start, end) 几乎可以看做等同于 slice 方法了,二者的语义不同,不过行为确实一致的,subarray 的语义表示返回原数组的某个范围的子数组,而 slice 的语义表示的裁切。同样 subarray 返回新的 Buffer 对象,并且返回的 Buffer 对象的 buffer 与原 Buffer 对象的 buffer 属性是相同的。

    const buffer = Buffer.from("hello world!");
    
    const newBuffer = buffer.subarray(6);
    console.log(newBuffer.toString()); // world!
    
    console.log(buffer.buffer === newBuffer.buffer); // true

    copy

    copy(target, [targetStart], [sourceStart], [sourceEnd]) 方法是将 source 从 sourceStart 到 sourceEnd 的内容复制到 target 从 targetStart 的位置,见下动图

    Node.js의 Buffer 객체 작업(생성, 읽기 및 쓰기)에 대한 자세한 설명

    除了 target 以外,其他三个参数都是可选参数,targetStart 与 sourceStart 的默认值为 0,sourceEnd 的默认值为 buf.length.

    const buf1 = Buffer.from("HelloWorld");
    const buf2 = Buffer.alloc(8);
    
    buf1.copy(buf2, 0, 1, 9);
    
    console.log(buf2.toString()); // elloWorl

    includes

    buf.includes(value, [offset], [encoding]) 方法的作用是判断 value 是否在 buf 中。

    value 可以是一个字符串,也可以是一个 Buffer 对象,也可以是一个整数;offset 用来规定查找范围,表示从 offset 处开始查找,默认为 0;enconding 表示编码,默认为 utf-8

    const buf = Buffer.from("HelloWorld");
    
    // 默认从 0 开始搜索
    console.log(buf.includes("H")); // true
    // 从 1 开始搜索,后面不包含 H
    console.log(buf.includes("H", 1)); // false
    
    console.log(buf.includes(Buffer.from("Hello"))); // true
    
    // H 对应的 utf-8 编码为 72
    console.log(buf.includes(72)); // true

    indexOf

    buf.indexOf(value, [offset], [encoding]) 是用来查找 value 在 buf 中的下标的,参数的含义同 includes 方法相同,如果在 buf 找不到 value,那么会返回 -1,所以 includes(value) 方法其实就相当于 indexOf(value) !== -1

    const buf = Buffer.from("HelloWorld");
    
    console.log(buf.indexOf("H")); // 0
    console.log(buf.indexOf("H", 1)); // -1
    console.log(buf.indexOf(Buffer.from("World"))); // 5
    console.log(buf.indexOf(72)); // 0

    equals

    buf.equals(otherBuffer) 是比较两个 Buffer 对象的字节是否完全相同,如果相同,则返回 true,否则返回 false

    const buf1 = Buffer.alloc(5);
    const buf2 = Buffer.alloc(5);
    const buf3 = Buffer.allocUnsafe(5);
    
    console.log(buf1.equals(buf2)); // true
    console.log(buf1.equals(buf3)); // false

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

    위 내용은 Node.js의 Buffer 객체 작업(생성, 읽기 및 쓰기)에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    성명:
    이 기사는 juejin.cn에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제