Node.js v25.0.0 文件
- Node.js v25.0.0
-
目錄
- 緩衝區
- 緩衝區與字元編碼
- 緩衝區與 TypedArray
- 緩衝區與迭代
- 類:
Blob - 類:
Buffer- 靜態方法:
Buffer.alloc(size[, fill[, encoding]]) - 靜態方法:
Buffer.allocUnsafe(size) - 靜態方法:
Buffer.allocUnsafeSlow(size) - 靜態方法:
Buffer.byteLength(string[, encoding]) - 靜態方法:
Buffer.compare(buf1, buf2) - 靜態方法:
Buffer.concat(list[, totalLength]) - 靜態方法:
Buffer.copyBytesFrom(view[, offset[, length]]) - 靜態方法:
Buffer.from(array) - 靜態方法:
Buffer.from(arrayBuffer[, byteOffset[, length]]) - 靜態方法:
Buffer.from(buffer) - 靜態方法:
Buffer.from(object[, offsetOrEncoding[, length]]) - 靜態方法:
Buffer.from(string[, encoding]) - 靜態方法:
Buffer.isBuffer(obj) - 靜態方法:
Buffer.isEncoding(encoding) Buffer.poolSizebuf[index]buf.bufferbuf.byteOffsetbuf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])buf.entries()buf.equals(otherBuffer)buf.fill(value[, offset[, end]][, encoding])buf.includes(value[, byteOffset][, encoding])buf.indexOf(value[, byteOffset][, encoding])buf.keys()buf.lastIndexOf(value[, byteOffset][, encoding])buf.lengthbuf.parentbuf.readBigInt64BE([offset])buf.readBigInt64LE([offset])buf.readBigUInt64BE([offset])buf.readBigUInt64LE([offset])buf.readDoubleBE([offset])buf.readDoubleLE([offset])buf.readFloatBE([offset])buf.readFloatLE([offset])buf.readInt8([offset])buf.readInt16BE([offset])buf.readInt16LE([offset])buf.readInt32BE([offset])buf.readInt32LE([offset])buf.readIntBE(offset, byteLength)buf.readIntLE(offset, byteLength)buf.readUInt8([offset])buf.readUInt16BE([offset])buf.readUInt16LE([offset])buf.readUInt32BE([offset])buf.readUInt32LE([offset])buf.readUIntBE(offset, byteLength)buf.readUIntLE(offset, byteLength)buf.subarray([start[, end]])buf.slice([start[, end]])buf.swap16()buf.swap32()buf.swap64()buf.toJSON()buf.toString([encoding[, start[, end]]])buf.values()buf.write(string[, offset[, length]][, encoding])buf.writeBigInt64BE(value[, offset])buf.writeBigInt64LE(value[, offset])buf.writeBigUInt64BE(value[, offset])buf.writeBigUInt64LE(value[, offset])buf.writeDoubleBE(value[, offset])buf.writeDoubleLE(value[, offset])buf.writeFloatBE(value[, offset])buf.writeFloatLE(value[, offset])buf.writeInt8(value[, offset])buf.writeInt16BE(value[, offset])buf.writeInt16LE(value[, offset])buf.writeInt32BE(value[, offset])buf.writeInt32LE(value[, offset])buf.writeIntBE(value, offset, byteLength)buf.writeIntLE(value, offset, byteLength)buf.writeUInt8(value[, offset])buf.writeUInt16BE(value[, offset])buf.writeUInt16LE(value[, offset])buf.writeUInt32BE(value[, offset])buf.writeUInt32LE(value[, offset])buf.writeUIntBE(value, offset, byteLength)buf.writeUIntLE(value, offset, byteLength)new Buffer(array)new Buffer(arrayBuffer[, byteOffset[, length]])new Buffer(buffer)new Buffer(size)new Buffer(string[, encoding])
- 靜態方法:
- 類:
File node:buffer模組 APIBuffer.from()、Buffer.alloc()和Buffer.allocUnsafe()
- 緩衝區
-
索引
- 斷言測試
- 非同步上下文跟蹤
- 非同步鉤子
- 緩衝區
- C++ 外掛
- 使用 Node-API 的 C/C++ 外掛
- C++ 嵌入器 API
- 子程序
- 叢集
- 命令列選項
- 控制檯
- 加密
- 偵錯程式
- 已棄用的 API
- 診斷通道
- DNS
- 域
- 環境變數
- 錯誤
- 事件
- 檔案系統
- 全域性物件
- HTTP
- HTTP/2
- HTTPS
- 檢查器
- 國際化
- 模組:CommonJS 模組
- 模組:ECMAScript 模組
- 模組:
node:moduleAPI - 模組:包
- 模組:TypeScript
- 網路
- 作業系統
- 路徑
- 效能鉤子
- 許可權
- 程序
- Punycode
- 查詢字串
- 逐行讀取
- REPL
- 報告
- 單一可執行檔案應用
- SQLite
- 流
- 字串解碼器
- 測試執行器
- 定時器
- TLS/SSL
- 跟蹤事件
- TTY
- UDP/資料報
- URL
- 實用工具
- V8
- 虛擬機器
- WASI
- Web Crypto API
- Web Streams API
- 工作執行緒
- Zlib
- 其他版本
- 選項
Buffer#
原始碼:lib/buffer.js
Buffer 物件用於表示一個固定長度的位元組序列。許多 Node.js API 都支援 Buffer。
Buffer 類是 JavaScript 的 <Uint8Array> 類的子類,並用涵蓋額外用例的方法對其進行了擴充套件。只要 Buffer 被支援,Node.js API 也會接受普通的 <Uint8Array>。
雖然 Buffer 類在全域性作用域內可用,但仍然建議透過 import 或 require 語句顯式引用它。
import { Buffer } from 'node:buffer';
// Creates a zero-filled Buffer of length 10.
const buf1 = Buffer.alloc(10);
// Creates a Buffer of length 10,
// filled with bytes which all have the value `1`.
const buf2 = Buffer.alloc(10, 1);
// Creates an uninitialized buffer of length 10.
// This is faster than calling Buffer.alloc() but the returned
// Buffer instance might contain old data that needs to be
// overwritten using fill(), write(), or other functions that fill the Buffer's
// contents.
const buf3 = Buffer.allocUnsafe(10);
// Creates a Buffer containing the bytes [1, 2, 3].
const buf4 = Buffer.from([1, 2, 3]);
// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
// are all truncated using `(value & 255)` to fit into the range 0–255.
const buf5 = Buffer.from([257, 257.5, -255, '1']);
// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
// [116, 195, 169, 115, 116] (in decimal notation)
const buf6 = Buffer.from('tést');
// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
const buf7 = Buffer.from('tést', 'latin1');const { Buffer } = require('node:buffer');
// Creates a zero-filled Buffer of length 10.
const buf1 = Buffer.alloc(10);
// Creates a Buffer of length 10,
// filled with bytes which all have the value `1`.
const buf2 = Buffer.alloc(10, 1);
// Creates an uninitialized buffer of length 10.
// This is faster than calling Buffer.alloc() but the returned
// Buffer instance might contain old data that needs to be
// overwritten using fill(), write(), or other functions that fill the Buffer's
// contents.
const buf3 = Buffer.allocUnsafe(10);
// Creates a Buffer containing the bytes [1, 2, 3].
const buf4 = Buffer.from([1, 2, 3]);
// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
// are all truncated using `(value & 255)` to fit into the range 0–255.
const buf5 = Buffer.from([257, 257.5, -255, '1']);
// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
// [116, 195, 169, 115, 116] (in decimal notation)
const buf6 = Buffer.from('tést');
// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
const buf7 = Buffer.from('tést', 'latin1');
緩衝區與字元編碼#
在 Buffer 和字串之間進行轉換時,可以指定字元編碼。如果未指定字元編碼,將預設使用 UTF-8。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('hello world', 'utf8');
console.log(buf.toString('hex'));
// Prints: 68656c6c6f20776f726c64
console.log(buf.toString('base64'));
// Prints: aGVsbG8gd29ybGQ=
console.log(Buffer.from('fhqwhgads', 'utf8'));
// Prints: <Buffer 66 68 71 77 68 67 61 64 73>
console.log(Buffer.from('fhqwhgads', 'utf16le'));
// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>const { Buffer } = require('node:buffer');
const buf = Buffer.from('hello world', 'utf8');
console.log(buf.toString('hex'));
// Prints: 68656c6c6f20776f726c64
console.log(buf.toString('base64'));
// Prints: aGVsbG8gd29ybGQ=
console.log(Buffer.from('fhqwhgads', 'utf8'));
// Prints: <Buffer 66 68 71 77 68 67 61 64 73>
console.log(Buffer.from('fhqwhgads', 'utf16le'));
// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>
Node.js 緩衝區接受其收到的編碼字串的所有大小寫變體。例如,UTF-8可以指定為 'utf8'、'UTF8' 或 'uTf8'。
Node.js 當前支援的字元編碼如下
-
'utf8'(別名:'utf-8'):多位元組編碼的 Unicode 字元。許多網頁和其他文件格式使用 UTF-8。這是預設的字元編碼。當將一個不完全包含有效 UTF-8 資料的Buffer解碼為字串時,將使用 Unicode 替換字元U+FFFD� 來表示這些錯誤。 -
'utf16le'(別名:'utf-16le'):多位元組編碼的 Unicode 字元。與'utf8'不同,字串中的每個字元都將使用 2 或 4 個位元組進行編碼。Node.js 只支援 UTF-16 的小端序變體。 -
'latin1':Latin-1 代表 ISO-8859-1。此字元編碼僅支援從U+0000到U+00FF的 Unicode 字元。每個字元使用單個位元組編碼。不在此範圍內的字元將被截斷並對映到該範圍內的字元。
使用上述編碼之一將 Buffer 轉換為字串稱為解碼,將字串轉換為 Buffer 稱為編碼。
Node.js 還支援以下二進位制到文字的編碼。對於二進位制到文字的編碼,命名約定是相反的:將 Buffer 轉換為字串通常稱為編碼,將字串轉換為 Buffer 稱為解碼。
-
'base64': Base64 編碼。從字串建立Buffer時,此編碼也會正確接受 RFC 4648 第 5 節中指定的“URL 和檔名安全字母表”。base64 編碼字串中包含的空格、製表符和換行符等空白字元將被忽略。 -
'base64url':RFC 4648 第 5 節中指定的 base64url 編碼。從字串建立Buffer時,此編碼也會正確接受常規的 base64 編碼字串。當將Buffer編碼為字串時,此編碼將省略填充。 -
'hex':將每個位元組編碼為兩個十六進位制字元。在解碼不完全由偶數個十六進位制字元組成的字串時,可能會發生資料截斷。請參閱下面的示例。
還支援以下舊式字元編碼
-
'ascii':僅適用於 7 位 ASCII 資料。當將字串編碼為Buffer時,這等同於使用'latin1'。當將Buffer解碼為字串時,使用此編碼會在解碼為'latin1'之前額外清除每個位元組的最高位。通常,沒有理由使用此編碼,因為在編碼或解碼純 ASCII 文字時,'utf8'(或者,如果已知資料始終為純 ASCII,則為'latin1')是更好的選擇。它僅為舊版相容性而提供。 -
'binary':'latin1'的別名。此編碼的名稱可能非常具有誤導性,因為這裡列出的所有編碼都在字串和二進位制資料之間進行轉換。對於字串和Buffer之間的轉換,通常'utf8'是正確的選擇。 -
'ucs2'、'ucs-2':'utf16le'的別名。UCS-2 過去指的是 UTF-16 的一個變體,不支援程式碼點大於 U+FFFF 的字元。在 Node.js 中,始終支援這些程式碼點。
import { Buffer } from 'node:buffer';
Buffer.from('1ag123', 'hex');
// Prints <Buffer 1a>, data truncated when first non-hexadecimal value
// ('g') encountered.
Buffer.from('1a7', 'hex');
// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').
Buffer.from('1634', 'hex');
// Prints <Buffer 16 34>, all data represented.const { Buffer } = require('node:buffer');
Buffer.from('1ag123', 'hex');
// Prints <Buffer 1a>, data truncated when first non-hexadecimal value
// ('g') encountered.
Buffer.from('1a7', 'hex');
// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').
Buffer.from('1634', 'hex');
// Prints <Buffer 16 34>, all data represented.
現代 Web 瀏覽器遵循 WHATWG 編碼標準,該標準將 'latin1' 和 'ISO-8859-1' 都別名為 'win-1252'。這意味著當執行像 http.get() 這樣的操作時,如果返回的字元集是 WHATWG 規範中列出的之一,伺服器可能實際上返回了 'win-1252' 編碼的資料,而使用 'latin1' 編碼可能會錯誤地解碼字元。
緩衝區與 TypedArray#
Buffer 例項也是 JavaScript <Uint8Array> 和 <TypedArray> 例項。所有 <TypedArray> 方法在 Buffer 上都可用。但是,Buffer API 和 <TypedArray> API 之間存在一些細微的不相容之處。
特別是
- 雖然
TypedArray.prototype.slice()建立TypedArray一部分的副本,但Buffer.prototype.slice()建立一個指向現有Buffer的檢視,而不進行復制。這種行為可能會令人意外,並且僅為舊版相容性而存在。可以使用TypedArray.prototype.subarray()在Buffer和其他TypedArray上實現Buffer.prototype.slice()的行為,並且應優先使用。 buf.toString()與其TypedArray等價物不相容。- 一些方法,例如
buf.indexOf(),支援額外的引數。
有兩種方法可以從 Buffer 建立新的 <TypedArray> 例項
- 將
Buffer傳遞給 <TypedArray> 建構函式將複製Buffer的內容,並將其解釋為整數陣列,而不是目標型別的位元組序列。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4]);
const uint32array = new Uint32Array(buf);
console.log(uint32array);
// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3, 4]);
const uint32array = new Uint32Array(buf);
console.log(uint32array);
// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]
- 傳遞
Buffer的底層 <ArrayBuffer> 將建立一個與Buffer共享記憶體的 <TypedArray>。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('hello', 'utf16le');
const uint16array = new Uint16Array(
buf.buffer,
buf.byteOffset,
buf.length / Uint16Array.BYTES_PER_ELEMENT);
console.log(uint16array);
// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]const { Buffer } = require('node:buffer');
const buf = Buffer.from('hello', 'utf16le');
const uint16array = new Uint16Array(
buf.buffer,
buf.byteOffset,
buf.length / Uint16Array.BYTES_PER_ELEMENT);
console.log(uint16array);
// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]
可以透過使用 TypedArray 物件的 .buffer 屬性,以相同的方式建立一個與 <TypedArray> 例項共享相同已分配記憶體的新 Buffer。在這種情況下,Buffer.from() 的行為類似於 new Uint8Array()。
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
// Copies the contents of `arr`.
const buf1 = Buffer.from(arr);
// Shares memory with `arr`.
const buf2 = Buffer.from(arr.buffer);
console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 a0 0f>
arr[1] = 6000;
console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 70 17>const { Buffer } = require('node:buffer');
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
// Copies the contents of `arr`.
const buf1 = Buffer.from(arr);
// Shares memory with `arr`.
const buf2 = Buffer.from(arr.buffer);
console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 a0 0f>
arr[1] = 6000;
console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 70 17>
當使用 <TypedArray> 的 .buffer 建立 Buffer 時,可以透過傳入 byteOffset 和 length 引數僅使用底層 <ArrayBuffer> 的一部分。
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(20);
const buf = Buffer.from(arr.buffer, 0, 16);
console.log(buf.length);
// Prints: 16const { Buffer } = require('node:buffer');
const arr = new Uint16Array(20);
const buf = Buffer.from(arr.buffer, 0, 16);
console.log(buf.length);
// Prints: 16
Buffer.from() 和 TypedArray.from() 具有不同的簽名和實現。具體來說,<TypedArray> 的變體接受第二個引數,該引數是一個對映函式,會對型別化陣列的每個元素呼叫
然而,Buffer.from() 方法不支援使用對映函式
緩衝區與迭代#
Buffer 例項可以使用 for..of 語法進行迭代
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3]);
for (const b of buf) {
console.log(b);
}
// Prints:
// 1
// 2
// 3const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3]);
for (const b of buf) {
console.log(b);
}
// Prints:
// 1
// 2
// 3
此外,可以使用 buf.values()、buf.keys() 和 buf.entries() 方法建立迭代器。
類:Blob#
一個 <Blob> 封裝了不可變的原始資料,可以安全地在多個工作執行緒之間共享。
new buffer.Blob([sources[, options]])#
sources<string[]> | <ArrayBuffer[]> | <TypedArray[]> | <DataView[]> | <Blob[]> 一個由字串、<ArrayBuffer>、<TypedArray>、<DataView> 或 <Blob> 物件組成的陣列,或任何這些物件的混合,它們將被儲存在Blob中。options<Object>
建立一個新的 Blob 物件,其中包含給定源的串聯。
<ArrayBuffer>、<TypedArray>、<DataView> 和 <Buffer> 源被複制到 'Blob' 中,因此在建立 'Blob' 後可以安全地修改它們。
字串源被編碼為 UTF-8 位元組序列並複製到 Blob 中。每個字串部分內未匹配的代理對將被 Unicode U+FFFD 替換字元替換。
blob.arrayBuffer()#
- 返回:<Promise>
返回一個 promise,該 promise 會兌現為一個包含 Blob 資料副本的 <ArrayBuffer>。
blob.bytes()#
blob.bytes() 方法以 Promise<Uint8Array> 的形式返回 Blob 物件的位元組。
const blob = new Blob(['hello']);
blob.bytes().then((bytes) => {
console.log(bytes); // Outputs: Uint8Array(5) [ 104, 101, 108, 108, 111 ]
});
blob.size#
Blob 的總大小(以位元組為單位)。
blob.slice([start[, end[, type]]])#
建立並返回一個包含此 Blob 物件資料子集的新 Blob。原始的 Blob 不會被改變。
Blob 物件與 MessageChannel#
一旦建立了 <Blob> 物件,它可以透過 MessagePort 傳送到多個目的地,而無需傳輸或立即複製資料。只有在呼叫 arrayBuffer() 或 text() 方法時,Blob 包含的資料才會被複制。
import { Blob } from 'node:buffer';
import { setTimeout as delay } from 'node:timers/promises';
const blob = new Blob(['hello there']);
const mc1 = new MessageChannel();
const mc2 = new MessageChannel();
mc1.port1.onmessage = async ({ data }) => {
console.log(await data.arrayBuffer());
mc1.port1.close();
};
mc2.port1.onmessage = async ({ data }) => {
await delay(1000);
console.log(await data.arrayBuffer());
mc2.port1.close();
};
mc1.port2.postMessage(blob);
mc2.port2.postMessage(blob);
// The Blob is still usable after posting.
blob.text().then(console.log);const { Blob } = require('node:buffer');
const { setTimeout: delay } = require('node:timers/promises');
const blob = new Blob(['hello there']);
const mc1 = new MessageChannel();
const mc2 = new MessageChannel();
mc1.port1.onmessage = async ({ data }) => {
console.log(await data.arrayBuffer());
mc1.port1.close();
};
mc2.port1.onmessage = async ({ data }) => {
await delay(1000);
console.log(await data.arrayBuffer());
mc2.port1.close();
};
mc1.port2.postMessage(blob);
mc2.port2.postMessage(blob);
// The Blob is still usable after posting.
blob.text().then(console.log);
類:Buffer#
Buffer 類是直接處理二進位制資料的全域性型別。它可以透過多種方式構造。
靜態方法:Buffer.alloc(size[, fill[, encoding]])#
size<integer> 新Buffer的期望長度。fill<string> | <Buffer> | <Uint8Array> | <integer> 用於預填充新Buffer的值。預設值:0。encoding<string> 如果fill是一個字串,這是它的編碼。預設值:'utf8'。- 返回:<Buffer>
分配一個大小為 size 位元組的新 Buffer。如果 fill 是 undefined,Buffer 將被零填充。
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(5);
console.log(buf);
// Prints: <Buffer 00 00 00 00 00>const { Buffer } = require('node:buffer');
const buf = Buffer.alloc(5);
console.log(buf);
// Prints: <Buffer 00 00 00 00 00>
如果 size 大於 buffer.constants.MAX_LENGTH 或小於 0,將丟擲 ERR_OUT_OF_RANGE。
如果指定了 fill,分配的 Buffer 將透過呼叫 buf.fill(fill) 進行初始化。
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(5, 'a');
console.log(buf);
// Prints: <Buffer 61 61 61 61 61>const { Buffer } = require('node:buffer');
const buf = Buffer.alloc(5, 'a');
console.log(buf);
// Prints: <Buffer 61 61 61 61 61>
如果同時指定了 fill 和 encoding,分配的 Buffer 將透過呼叫 buf.fill(fill, encoding) 進行初始化。
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
console.log(buf);
// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>const { Buffer } = require('node:buffer');
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
console.log(buf);
// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
呼叫 Buffer.alloc() 可能比其替代方案 Buffer.allocUnsafe() 慢得多,但能確保新建立的 Buffer 例項內容永遠不會包含先前分配的敏感資料,包括可能不是為 Buffer 分配的資料。
如果 size 不是數字,將丟擲 TypeError。
靜態方法:Buffer.allocUnsafe(size)#
分配一個大小為 size 位元組的新 Buffer。如果 size 大於 buffer.constants.MAX_LENGTH 或小於 0,則會丟擲 ERR_OUT_OF_RANGE。
以此方式建立的 Buffer 例項的底層記憶體未初始化。新建立的 Buffer 的內容是未知的,並且可能包含敏感資料。請改用 Buffer.alloc() 來用零初始化 Buffer 例項。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(10);
console.log(buf);
// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
buf.fill(0);
console.log(buf);
// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(10);
console.log(buf);
// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
buf.fill(0);
console.log(buf);
// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
如果 size 不是數字,將丟擲 TypeError。
Buffer 模組預分配一個大小為 Buffer.poolSize 的內部 Buffer 例項,該例項用作快速分配新 Buffer 例項的池,這些例項使用 Buffer.allocUnsafe()、Buffer.from(array)、Buffer.from(string) 和 Buffer.concat() 建立,僅當 size 小於 Buffer.poolSize >>> 1(Buffer.poolSize 除以二的向下取整)時。
使用這個預分配的內部記憶體池是呼叫 Buffer.alloc(size, fill) 與 Buffer.allocUnsafe(size).fill(fill) 之間的關鍵區別。具體來說,Buffer.alloc(size, fill) 將永遠不會使用內部 Buffer 池,而如果 size 小於或等於 Buffer.poolSize 的一半,Buffer.allocUnsafe(size).fill(fill) 將會使用內部 Buffer 池。這個差異很細微,但在應用程式需要 Buffer.allocUnsafe() 提供的額外效能時可能很重要。
靜態方法:Buffer.allocUnsafeSlow(size)#
分配一個大小為 size 位元組的新 Buffer。如果 size 大於 buffer.constants.MAX_LENGTH 或小於 0,則會丟擲 ERR_OUT_OF_RANGE。如果 size 為 0,則建立一個零長度的 Buffer。
以此方式建立的 Buffer 例項的底層記憶體未初始化。新建立的 Buffer 的內容是未知的,並且可能包含敏感資料。使用 buf.fill(0) 將此類 Buffer 例項用零進行初始化。
當使用 Buffer.allocUnsafe() 分配新的 Buffer 例項時,小於 Buffer.poolSize >>> 1(預設 poolSize 時為 4KiB)的分配是從單個預分配的 Buffer 中切片出來的。這使得應用程式可以避免因建立許多單獨分配的 Buffer 例項而產生的垃圾回收開銷。這種方法透過消除跟蹤和清理大量單個 ArrayBuffer 物件的需要,提高了效能和記憶體使用率。
然而,在開發者可能需要在一個不確定的時間內保留一小塊記憶體池的情況下,使用 Buffer.allocUnsafeSlow() 建立一個非池化的 Buffer 例項然後複製出相關位可能是合適的。
import { Buffer } from 'node:buffer';
// Need to keep around a few small chunks of memory.
const store = [];
socket.on('readable', () => {
let data;
while (null !== (data = readable.read())) {
// Allocate for retained data.
const sb = Buffer.allocUnsafeSlow(10);
// Copy the data into the new allocation.
data.copy(sb, 0, 0, 10);
store.push(sb);
}
});const { Buffer } = require('node:buffer');
// Need to keep around a few small chunks of memory.
const store = [];
socket.on('readable', () => {
let data;
while (null !== (data = readable.read())) {
// Allocate for retained data.
const sb = Buffer.allocUnsafeSlow(10);
// Copy the data into the new allocation.
data.copy(sb, 0, 0, 10);
store.push(sb);
}
});
如果 size 不是數字,將丟擲 TypeError。
靜態方法:Buffer.byteLength(string[, encoding])#
string<string> | <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <SharedArrayBuffer> 一個用於計算長度的值。encoding<string> 如果string是一個字串,這是它的編碼。預設值:'utf8'。- 返回:<integer>
string中包含的位元組數。
返回一個字串在使用 encoding 編碼時的位元組長度。這與 String.prototype.length 不同,後者不考慮用於將字串轉換為位元組的編碼。
對於 'base64'、'base64url' 和 'hex',此函式假定輸入有效。對於包含非 base64/hex 編碼資料(例如空格)的字串,返回值可能大於從該字串建立的 Buffer 的長度。
import { Buffer } from 'node:buffer';
const str = '\u00bd + \u00bc = \u00be';
console.log(`${str}: ${str.length} characters, ` +
`${Buffer.byteLength(str, 'utf8')} bytes`);
// Prints: ½ + ¼ = ¾: 9 characters, 12 bytesconst { Buffer } = require('node:buffer');
const str = '\u00bd + \u00bc = \u00be';
console.log(`${str}: ${str.length} characters, ` +
`${Buffer.byteLength(str, 'utf8')} bytes`);
// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
當 string 是 <Buffer> | <DataView> | <TypedArray> | <ArrayBuffer> | <SharedArrayBuffer> 時,返回其 .byteLength 報告的位元組長度。
靜態方法:Buffer.compare(buf1, buf2)#
buf1<Buffer> | <Uint8Array>buf2<Buffer> | <Uint8Array>- 返回:<integer>
-1、0或1,取決於比較結果。詳見buf.compare()。
比較 buf1 和 buf2,通常用於對 Buffer 例項陣列進行排序。這等同於呼叫 buf1.compare(buf2)。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('1234');
const buf2 = Buffer.from('0123');
const arr = [buf1, buf2];
console.log(arr.sort(Buffer.compare));
// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
// (This result is equal to: [buf2, buf1].)const { Buffer } = require('node:buffer');
const buf1 = Buffer.from('1234');
const buf2 = Buffer.from('0123');
const arr = [buf1, buf2];
console.log(arr.sort(Buffer.compare));
// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
// (This result is equal to: [buf2, buf1].)
靜態方法:Buffer.concat(list[, totalLength])#
list<Buffer[]> | <Uint8Array[]> 要連線的Buffer或 <Uint8Array> 例項列表。totalLength<integer> 連線後list中Buffer例項的總長度。- 返回:<Buffer>
返回一個新的 Buffer,它是將 list 中所有 Buffer 例項連線在一起的結果。
如果列表沒有專案,或者 totalLength 為 0,則返回一個新的零長度 Buffer。
如果未提供 totalLength,則透過將 list 中 Buffer 例項的長度相加來計算它。
如果提供了 totalLength,它會被強制轉換為一個無符號整數。如果 list 中 Buffer 的組合長度超過 totalLength,結果將被截斷為 totalLength。如果 list 中 Buffer 的組合長度小於 totalLength,剩餘的空間將用零填充。
import { Buffer } from 'node:buffer';
// Create a single `Buffer` from a list of three `Buffer` instances.
const buf1 = Buffer.alloc(10);
const buf2 = Buffer.alloc(14);
const buf3 = Buffer.alloc(18);
const totalLength = buf1.length + buf2.length + buf3.length;
console.log(totalLength);
// Prints: 42
const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
console.log(bufA);
// Prints: <Buffer 00 00 00 00 ...>
console.log(bufA.length);
// Prints: 42const { Buffer } = require('node:buffer');
// Create a single `Buffer` from a list of three `Buffer` instances.
const buf1 = Buffer.alloc(10);
const buf2 = Buffer.alloc(14);
const buf3 = Buffer.alloc(18);
const totalLength = buf1.length + buf2.length + buf3.length;
console.log(totalLength);
// Prints: 42
const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
console.log(bufA);
// Prints: <Buffer 00 00 00 00 ...>
console.log(bufA.length);
// Prints: 42
Buffer.concat() 也可能像 Buffer.allocUnsafe() 一樣使用內部的 Buffer 池。
靜態方法:Buffer.copyBytesFrom(view[, offset[, length]])#
view<TypedArray> 要複製的 <TypedArray>。offset<integer>view內的起始偏移量。預設值:0。length<integer> 從view複製的元素數量。預設值:view.length - offset。- 返回:<Buffer>
將 view 的底層記憶體複製到一個新的 Buffer 中。
const u16 = new Uint16Array([0, 0xffff]);
const buf = Buffer.copyBytesFrom(u16, 1, 1);
u16[1] = 0;
console.log(buf.length); // 2
console.log(buf[0]); // 255
console.log(buf[1]); // 255
靜態方法:Buffer.from(array)#
array<integer[]>- 返回:<Buffer>
使用一個範圍在 0 – 255 之間的位元組陣列 array 來分配一個新的 Buffer。超出該範圍的陣列條目將被截斷以適應它。
import { Buffer } from 'node:buffer';
// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);const { Buffer } = require('node:buffer');
// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
如果 array 是一個類陣列物件(即,具有 number 型別的 length 屬性的物件),則它被視為一個數組,除非它是一個 Buffer 或 Uint8Array。這意味著所有其他 TypedArray 變體都被視為一個 Array。要從支援 TypedArray 的位元組建立一個 Buffer,請使用 Buffer.copyBytesFrom()。
如果 array 不是一個 Array 或適用於 Buffer.from() 變體的其他型別,將丟擲 TypeError。
Buffer.from(array) 和 Buffer.from(string) 也可能像 Buffer.allocUnsafe() 一樣使用內部的 Buffer 池。
靜態方法:Buffer.from(arrayBuffer[, byteOffset[, length]])#
arrayBuffer<ArrayBuffer> | <SharedArrayBuffer> 一個 <ArrayBuffer>、<SharedArrayBuffer>,例如 <TypedArray> 的.buffer屬性。byteOffset<integer> 要暴露的第一個位元組的索引。預設值:0。length<integer> 要暴露的位元組數。預設值:arrayBuffer.byteLength - byteOffset。- 返回:<Buffer>
這將建立 <ArrayBuffer> 的檢視,而不復制底層記憶體。例如,當傳遞一個對 <TypedArray> 例項的 .buffer 屬性的引用時,新建立的 Buffer 將與 <TypedArray> 的底層 ArrayBuffer 共享相同的已分配記憶體。
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
// Shares memory with `arr`.
const buf = Buffer.from(arr.buffer);
console.log(buf);
// Prints: <Buffer 88 13 a0 0f>
// Changing the original Uint16Array changes the Buffer also.
arr[1] = 6000;
console.log(buf);
// Prints: <Buffer 88 13 70 17>const { Buffer } = require('node:buffer');
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
// Shares memory with `arr`.
const buf = Buffer.from(arr.buffer);
console.log(buf);
// Prints: <Buffer 88 13 a0 0f>
// Changing the original Uint16Array changes the Buffer also.
arr[1] = 6000;
console.log(buf);
// Prints: <Buffer 88 13 70 17>
可選的 byteOffset 和 length 引數指定 arrayBuffer 內的一個記憶體範圍,該範圍將由 Buffer 共享。
import { Buffer } from 'node:buffer';
const ab = new ArrayBuffer(10);
const buf = Buffer.from(ab, 0, 2);
console.log(buf.length);
// Prints: 2const { Buffer } = require('node:buffer');
const ab = new ArrayBuffer(10);
const buf = Buffer.from(ab, 0, 2);
console.log(buf.length);
// Prints: 2
如果 arrayBuffer 不是 <ArrayBuffer> 或 <SharedArrayBuffer> 或其他適合 Buffer.from() 變體的型別,則會丟擲 TypeError。
重要的是要記住,一個後備的 ArrayBuffer 可以覆蓋一個超出 TypedArray 檢視邊界的記憶體範圍。使用 TypedArray 的 buffer 屬性建立的新 Buffer 可能會超出 TypedArray 的範圍
import { Buffer } from 'node:buffer';
const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
console.log(arrA.buffer === arrB.buffer); // true
const buf = Buffer.from(arrB.buffer);
console.log(buf);
// Prints: <Buffer 63 64 65 66>const { Buffer } = require('node:buffer');
const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
console.log(arrA.buffer === arrB.buffer); // true
const buf = Buffer.from(arrB.buffer);
console.log(buf);
// Prints: <Buffer 63 64 65 66>
靜態方法:Buffer.from(buffer)#
buffer<Buffer> | <Uint8Array> 一個現有的Buffer或 <Uint8Array>,從中複製資料。- 返回:<Buffer>
將傳遞的 buffer 資料複製到一個新的 Buffer 例項中。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);
buf1[0] = 0x61;
console.log(buf1.toString());
// Prints: auffer
console.log(buf2.toString());
// Prints: bufferconst { Buffer } = require('node:buffer');
const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);
buf1[0] = 0x61;
console.log(buf1.toString());
// Prints: auffer
console.log(buf2.toString());
// Prints: buffer
如果 buffer 不是一個 Buffer 或其他適合 Buffer.from() 變體的型別,將丟擲 TypeError。
靜態方法:Buffer.from(object[, offsetOrEncoding[, length]])#
object<Object> 一個支援Symbol.toPrimitive或valueOf()的物件。offsetOrEncoding<integer> | <string> 一個位元組偏移量或編碼。length<integer> 一個長度。- 返回:<Buffer>
對於其 valueOf() 函式返回值不嚴格等於 object 的物件,返回 Buffer.from(object.valueOf(), offsetOrEncoding, length)。
import { Buffer } from 'node:buffer';
const buf = Buffer.from(new String('this is a test'));
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>const { Buffer } = require('node:buffer');
const buf = Buffer.from(new String('this is a test'));
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
對於支援 Symbol.toPrimitive 的物件,返回 Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding)。
import { Buffer } from 'node:buffer';
class Foo {
[Symbol.toPrimitive]() {
return 'this is a test';
}
}
const buf = Buffer.from(new Foo(), 'utf8');
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>const { Buffer } = require('node:buffer');
class Foo {
[Symbol.toPrimitive]() {
return 'this is a test';
}
}
const buf = Buffer.from(new Foo(), 'utf8');
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
如果 object 沒有上述方法,或者不是適合 Buffer.from() 變體的其他型別,將丟擲 TypeError。
靜態方法:Buffer.from(string[, encoding])#
建立一個包含 string 的新 Buffer。encoding 引數標識了將 string 轉換為位元組時要使用的字元編碼。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('this is a tést');
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
console.log(buf1.toString());
// Prints: this is a tést
console.log(buf2.toString());
// Prints: this is a tést
console.log(buf1.toString('latin1'));
// Prints: this is a téstconst { Buffer } = require('node:buffer');
const buf1 = Buffer.from('this is a tést');
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
console.log(buf1.toString());
// Prints: this is a tést
console.log(buf2.toString());
// Prints: this is a tést
console.log(buf1.toString('latin1'));
// Prints: this is a tést
如果 string 不是一個字串或適用於 Buffer.from() 變體的其他型別,將丟擲 TypeError。
Buffer.from(string) 也可能像 Buffer.allocUnsafe() 一樣使用內部的 Buffer 池。
靜態方法:Buffer.isBuffer(obj)#
如果 obj 是一個 Buffer,則返回 true,否則返回 false。
import { Buffer } from 'node:buffer';
Buffer.isBuffer(Buffer.alloc(10)); // true
Buffer.isBuffer(Buffer.from('foo')); // true
Buffer.isBuffer('a string'); // false
Buffer.isBuffer([]); // false
Buffer.isBuffer(new Uint8Array(1024)); // falseconst { Buffer } = require('node:buffer');
Buffer.isBuffer(Buffer.alloc(10)); // true
Buffer.isBuffer(Buffer.from('foo')); // true
Buffer.isBuffer('a string'); // false
Buffer.isBuffer([]); // false
Buffer.isBuffer(new Uint8Array(1024)); // false
靜態方法:Buffer.isEncoding(encoding)#
如果 encoding 是支援的字元編碼的名稱,則返回 true,否則返回 false。
import { Buffer } from 'node:buffer';
console.log(Buffer.isEncoding('utf8'));
// Prints: true
console.log(Buffer.isEncoding('hex'));
// Prints: true
console.log(Buffer.isEncoding('utf/8'));
// Prints: false
console.log(Buffer.isEncoding(''));
// Prints: falseconst { Buffer } = require('node:buffer');
console.log(Buffer.isEncoding('utf8'));
// Prints: true
console.log(Buffer.isEncoding('hex'));
// Prints: true
console.log(Buffer.isEncoding('utf/8'));
// Prints: false
console.log(Buffer.isEncoding(''));
// Prints: false
buf[index]#
index<integer>
索引運算子 [index] 可用於獲取和設定 buf 中位置 index 處的八位位元組。這些值指的是單個位元組,因此合法的值範圍在 0x00 和 0xFF(十六進位制)或 0 和 255(十進位制)之間。
這個運算子繼承自 Uint8Array,因此它在越界訪問時的行為與 Uint8Array 相同。換句話說,當 index 為負或大於等於 buf.length 時,buf[index] 返回 undefined,而當 index 為負或 >= buf.length 時,buf[index] = value 不會修改緩衝區。
import { Buffer } from 'node:buffer';
// Copy an ASCII string into a `Buffer` one byte at a time.
// (This only works for ASCII-only strings. In general, one should use
// `Buffer.from()` to perform this conversion.)
const str = 'Node.js';
const buf = Buffer.allocUnsafe(str.length);
for (let i = 0; i < str.length; i++) {
buf[i] = str.charCodeAt(i);
}
console.log(buf.toString('utf8'));
// Prints: Node.jsconst { Buffer } = require('node:buffer');
// Copy an ASCII string into a `Buffer` one byte at a time.
// (This only works for ASCII-only strings. In general, one should use
// `Buffer.from()` to perform this conversion.)
const str = 'Node.js';
const buf = Buffer.allocUnsafe(str.length);
for (let i = 0; i < str.length; i++) {
buf[i] = str.charCodeAt(i);
}
console.log(buf.toString('utf8'));
// Prints: Node.js
buf.buffer#
- 型別:<ArrayBuffer> 建立此
Buffer物件所基於的底層ArrayBuffer物件。
不保證此 ArrayBuffer 與原始 Buffer 完全對應。詳見關於 buf.byteOffset 的說明。
import { Buffer } from 'node:buffer';
const arrayBuffer = new ArrayBuffer(16);
const buffer = Buffer.from(arrayBuffer);
console.log(buffer.buffer === arrayBuffer);
// Prints: trueconst { Buffer } = require('node:buffer');
const arrayBuffer = new ArrayBuffer(16);
const buffer = Buffer.from(arrayBuffer);
console.log(buffer.buffer === arrayBuffer);
// Prints: true
buf.byteOffset#
- 型別:<integer>
Buffer的底層ArrayBuffer物件的byteOffset。
當在 Buffer.from(ArrayBuffer, byteOffset, length) 中設定 byteOffset 時,或者有時在分配小於 Buffer.poolSize 的 Buffer 時,緩衝區不會從底層 ArrayBuffer 的零偏移量開始。
當使用 buf.buffer 直接訪問底層 ArrayBuffer 時,這可能會導致問題,因為 ArrayBuffer 的其他部分可能與 Buffer 物件本身無關。
建立一個與 Buffer 共享記憶體的 TypedArray 物件時的一個常見問題是,在這種情況下,需要正確指定 byteOffset
import { Buffer } from 'node:buffer';
// Create a buffer smaller than `Buffer.poolSize`.
const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
// When casting the Node.js Buffer to an Int8Array, use the byteOffset
// to refer only to the part of `nodeBuffer.buffer` that contains the memory
// for `nodeBuffer`.
new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);const { Buffer } = require('node:buffer');
// Create a buffer smaller than `Buffer.poolSize`.
const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
// When casting the Node.js Buffer to an Int8Array, use the byteOffset
// to refer only to the part of `nodeBuffer.buffer` that contains the memory
// for `nodeBuffer`.
new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])#
target<Buffer> | <Uint8Array> 一個與buf進行比較的Buffer或 <Uint8Array>。targetStart<integer> 在target中開始比較的偏移量。預設值:0。targetEnd<integer> 在target中結束比較的偏移量(不包括)。預設值:target.length。sourceStart<integer> 在buf中開始比較的偏移量。預設值:0。sourceEnd<integer> 在buf中結束比較的偏移量(不包括)。預設值:buf.length。- 返回:<integer>
將 buf 與 target 進行比較,並返回一個數字,指示 buf 在排序順序中是位於 target 之前、之後還是與之相同。比較基於每個 Buffer 中的實際位元組序列。
- 如果
target與buf相同,則返回0。 - 如果排序時
target應該排在buf之前,則返回1。 - 如果排序時
target應該排在buf之後,則返回-1。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('BCD');
const buf3 = Buffer.from('ABCD');
console.log(buf1.compare(buf1));
// Prints: 0
console.log(buf1.compare(buf2));
// Prints: -1
console.log(buf1.compare(buf3));
// Prints: -1
console.log(buf2.compare(buf1));
// Prints: 1
console.log(buf2.compare(buf3));
// Prints: 1
console.log([buf1, buf2, buf3].sort(Buffer.compare));
// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
// (This result is equal to: [buf1, buf3, buf2].)const { Buffer } = require('node:buffer');
const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('BCD');
const buf3 = Buffer.from('ABCD');
console.log(buf1.compare(buf1));
// Prints: 0
console.log(buf1.compare(buf2));
// Prints: -1
console.log(buf1.compare(buf3));
// Prints: -1
console.log(buf2.compare(buf1));
// Prints: 1
console.log(buf2.compare(buf3));
// Prints: 1
console.log([buf1, buf2, buf3].sort(Buffer.compare));
// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
// (This result is equal to: [buf1, buf3, buf2].)
可選的 targetStart、targetEnd、sourceStart 和 sourceEnd 引數可用於將比較限制在 target 和 buf 各自的特定範圍內。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
console.log(buf1.compare(buf2, 5, 9, 0, 4));
// Prints: 0
console.log(buf1.compare(buf2, 0, 6, 4));
// Prints: -1
console.log(buf1.compare(buf2, 5, 6, 5));
// Prints: 1const { Buffer } = require('node:buffer');
const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
console.log(buf1.compare(buf2, 5, 9, 0, 4));
// Prints: 0
console.log(buf1.compare(buf2, 0, 6, 4));
// Prints: -1
console.log(buf1.compare(buf2, 5, 6, 5));
// Prints: 1
如果 targetStart < 0、sourceStart < 0、targetEnd > target.byteLength 或 sourceEnd > source.byteLength,則會丟擲 ERR_OUT_OF_RANGE。
buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])#
target<Buffer> | <Uint8Array> 要複製到的Buffer或 <Uint8Array>。targetStart<integer> 在target中開始寫入的偏移量。預設值:0。sourceStart<integer> 在buf中開始複製的偏移量。預設值:0。sourceEnd<integer> 在buf中停止複製的偏移量(不包括)。預設值:buf.length。- 返回:<integer> 複製的位元組數。
將資料從 buf 的一個區域複製到 target 的一個區域,即使 target 的記憶體區域與 buf 重疊。
TypedArray.prototype.set() 執行相同的操作,並且對所有 TypedArray(包括 Node.js 的 Buffer)都可用,儘管它接受不同的函式引數。
import { Buffer } from 'node:buffer';
// Create two `Buffer` instances.
const buf1 = Buffer.allocUnsafe(26);
const buf2 = Buffer.allocUnsafe(26).fill('!');
for (let i = 0; i < 26; i++) {
// 97 is the decimal ASCII value for 'a'.
buf1[i] = i + 97;
}
// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
buf1.copy(buf2, 8, 16, 20);
// This is equivalent to:
// buf2.set(buf1.subarray(16, 20), 8);
console.log(buf2.toString('ascii', 0, 25));
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!const { Buffer } = require('node:buffer');
// Create two `Buffer` instances.
const buf1 = Buffer.allocUnsafe(26);
const buf2 = Buffer.allocUnsafe(26).fill('!');
for (let i = 0; i < 26; i++) {
// 97 is the decimal ASCII value for 'a'.
buf1[i] = i + 97;
}
// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
buf1.copy(buf2, 8, 16, 20);
// This is equivalent to:
// buf2.set(buf1.subarray(16, 20), 8);
console.log(buf2.toString('ascii', 0, 25));
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
import { Buffer } from 'node:buffer';
// Create a `Buffer` and copy data from one region to an overlapping region
// within the same `Buffer`.
const buf = Buffer.allocUnsafe(26);
for (let i = 0; i < 26; i++) {
// 97 is the decimal ASCII value for 'a'.
buf[i] = i + 97;
}
buf.copy(buf, 0, 4, 10);
console.log(buf.toString());
// Prints: efghijghijklmnopqrstuvwxyzconst { Buffer } = require('node:buffer');
// Create a `Buffer` and copy data from one region to an overlapping region
// within the same `Buffer`.
const buf = Buffer.allocUnsafe(26);
for (let i = 0; i < 26; i++) {
// 97 is the decimal ASCII value for 'a'.
buf[i] = i + 97;
}
buf.copy(buf, 0, 4, 10);
console.log(buf.toString());
// Prints: efghijghijklmnopqrstuvwxyz
buf.entries()#
- 返回:<Iterator>
從 buf 的內容中建立並返回一個 [index, byte] 對的迭代器。
import { Buffer } from 'node:buffer';
// Log the entire contents of a `Buffer`.
const buf = Buffer.from('buffer');
for (const pair of buf.entries()) {
console.log(pair);
}
// Prints:
// [0, 98]
// [1, 117]
// [2, 102]
// [3, 102]
// [4, 101]
// [5, 114]const { Buffer } = require('node:buffer');
// Log the entire contents of a `Buffer`.
const buf = Buffer.from('buffer');
for (const pair of buf.entries()) {
console.log(pair);
}
// Prints:
// [0, 98]
// [1, 117]
// [2, 102]
// [3, 102]
// [4, 101]
// [5, 114]
buf.equals(otherBuffer)#
otherBuffer<Buffer> | <Uint8Array> 一個與buf進行比較的Buffer或 <Uint8Array>。- 返回:<boolean>
如果 buf 和 otherBuffer 的位元組完全相同,則返回 true,否則返回 false。等價於 buf.compare(otherBuffer) === 0。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('414243', 'hex');
const buf3 = Buffer.from('ABCD');
console.log(buf1.equals(buf2));
// Prints: true
console.log(buf1.equals(buf3));
// Prints: falseconst { Buffer } = require('node:buffer');
const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('414243', 'hex');
const buf3 = Buffer.from('ABCD');
console.log(buf1.equals(buf2));
// Prints: true
console.log(buf1.equals(buf3));
// Prints: false
buf.fill(value[, offset[, end]][, encoding])#
value<string> | <Buffer> | <Uint8Array> | <integer> 用於填充buf的值。空值(字串、Uint8Array、Buffer)被強制轉換為0。offset<integer> 在開始填充buf之前要跳過的位元組數。預設值:0。end<integer> 在哪裡停止填充buf(不包括)。預設值:buf.length。encoding<string> 如果value是字串,則為其編碼。預設值:'utf8'。- 返回:<Buffer> 對
buf的引用。
用指定的 value 填充 buf。如果未給出 offset 和 end,則將填充整個 buf。
import { Buffer } from 'node:buffer';
// Fill a `Buffer` with the ASCII character 'h'.
const b = Buffer.allocUnsafe(50).fill('h');
console.log(b.toString());
// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
// Fill a buffer with empty string
const c = Buffer.allocUnsafe(5).fill('');
console.log(c.fill(''));
// Prints: <Buffer 00 00 00 00 00>const { Buffer } = require('node:buffer');
// Fill a `Buffer` with the ASCII character 'h'.
const b = Buffer.allocUnsafe(50).fill('h');
console.log(b.toString());
// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
// Fill a buffer with empty string
const c = Buffer.allocUnsafe(5).fill('');
console.log(c.fill(''));
// Prints: <Buffer 00 00 00 00 00>
如果 value 不是字串、Buffer 或整數,它會被強制轉換為一個 uint32 值。如果結果整數大於 255(十進位制),buf 將被填充為 value & 255。
如果 fill() 操作的最後一次寫入落在一個多位元組字元上,那麼只有該字元中能放入 buf 的位元組會被寫入。
import { Buffer } from 'node:buffer';
// Fill a `Buffer` with character that takes up two bytes in UTF-8.
console.log(Buffer.allocUnsafe(5).fill('\u0222'));
// Prints: <Buffer c8 a2 c8 a2 c8>const { Buffer } = require('node:buffer');
// Fill a `Buffer` with character that takes up two bytes in UTF-8.
console.log(Buffer.allocUnsafe(5).fill('\u0222'));
// Prints: <Buffer c8 a2 c8 a2 c8>
如果 value 包含無效字元,它將被截斷;如果沒有剩餘的有效填充資料,則會丟擲異常。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(5);
console.log(buf.fill('a'));
// Prints: <Buffer 61 61 61 61 61>
console.log(buf.fill('aazz', 'hex'));
// Prints: <Buffer aa aa aa aa aa>
console.log(buf.fill('zz', 'hex'));
// Throws an exception.const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(5);
console.log(buf.fill('a'));
// Prints: <Buffer 61 61 61 61 61>
console.log(buf.fill('aazz', 'hex'));
// Prints: <Buffer aa aa aa aa aa>
console.log(buf.fill('zz', 'hex'));
// Throws an exception.
buf.includes(value[, byteOffset][, encoding])#
value<string> | <Buffer> | <Uint8Array> | <integer> 要搜尋的內容。byteOffset<integer> 在buf中開始搜尋的位置。如果為負數,則偏移量從buf的末尾計算。預設值:0。encoding<string> 如果value是一個字串,這是它的編碼。預設值:'utf8'。- 返回:<boolean> 如果在
buf中找到value,則為true,否則為false。
等價於 buf.indexOf() !== -1。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this is a buffer');
console.log(buf.includes('this'));
// Prints: true
console.log(buf.includes('is'));
// Prints: true
console.log(buf.includes(Buffer.from('a buffer')));
// Prints: true
console.log(buf.includes(97));
// Prints: true (97 is the decimal ASCII value for 'a')
console.log(buf.includes(Buffer.from('a buffer example')));
// Prints: false
console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
// Prints: true
console.log(buf.includes('this', 4));
// Prints: falseconst { Buffer } = require('node:buffer');
const buf = Buffer.from('this is a buffer');
console.log(buf.includes('this'));
// Prints: true
console.log(buf.includes('is'));
// Prints: true
console.log(buf.includes(Buffer.from('a buffer')));
// Prints: true
console.log(buf.includes(97));
// Prints: true (97 is the decimal ASCII value for 'a')
console.log(buf.includes(Buffer.from('a buffer example')));
// Prints: false
console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
// Prints: true
console.log(buf.includes('this', 4));
// Prints: false
buf.indexOf(value[, byteOffset][, encoding])#
value<string> | <Buffer> | <Uint8Array> | <integer> 要搜尋的內容。byteOffset<integer> 在buf中開始搜尋的位置。如果為負數,則偏移量從buf的末尾計算。預設值:0。encoding<string> 如果value是一個字串,這是用於確定將在buf中搜索的字串的二進位制表示的編碼。預設值:'utf8'。- 返回:<integer>
buf中第一次出現value的索引,如果buf不包含value,則返回-1。
如果 value 是
- 一個字串,
value根據encoding中的字元編碼進行解釋。 - 一個
Buffer或 <Uint8Array>,value將被完整使用。要比較部分Buffer,請使用buf.subarray。 - 一個數字,
value將被解釋為0到255之間的無符號 8 位整數值。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this is a buffer');
console.log(buf.indexOf('this'));
// Prints: 0
console.log(buf.indexOf('is'));
// Prints: 2
console.log(buf.indexOf(Buffer.from('a buffer')));
// Prints: 8
console.log(buf.indexOf(97));
// Prints: 8 (97 is the decimal ASCII value for 'a')
console.log(buf.indexOf(Buffer.from('a buffer example')));
// Prints: -1
console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
// Prints: 8
const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
// Prints: 4
console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
// Prints: 6const { Buffer } = require('node:buffer');
const buf = Buffer.from('this is a buffer');
console.log(buf.indexOf('this'));
// Prints: 0
console.log(buf.indexOf('is'));
// Prints: 2
console.log(buf.indexOf(Buffer.from('a buffer')));
// Prints: 8
console.log(buf.indexOf(97));
// Prints: 8 (97 is the decimal ASCII value for 'a')
console.log(buf.indexOf(Buffer.from('a buffer example')));
// Prints: -1
console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
// Prints: 8
const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
// Prints: 4
console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
// Prints: 6
如果 value 不是字串、數字或 Buffer,此方法將丟擲 TypeError。如果 value 是一個數字,它將被強制轉換為一個有效的位元組值,即 0 到 255 之間的整數。
如果 byteOffset 不是數字,它將被強制轉換為數字。如果強制轉換的結果是 NaN 或 0,則將搜尋整個緩衝區。此行為與 String.prototype.indexOf() 匹配。
import { Buffer } from 'node:buffer';
const b = Buffer.from('abcdef');
// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.indexOf(99.9));
console.log(b.indexOf(256 + 99));
// Passing a byteOffset that coerces to NaN or 0.
// Prints: 1, searching the whole buffer.
console.log(b.indexOf('b', undefined));
console.log(b.indexOf('b', {}));
console.log(b.indexOf('b', null));
console.log(b.indexOf('b', []));const { Buffer } = require('node:buffer');
const b = Buffer.from('abcdef');
// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.indexOf(99.9));
console.log(b.indexOf(256 + 99));
// Passing a byteOffset that coerces to NaN or 0.
// Prints: 1, searching the whole buffer.
console.log(b.indexOf('b', undefined));
console.log(b.indexOf('b', {}));
console.log(b.indexOf('b', null));
console.log(b.indexOf('b', []));
如果 value 是一個空字串或空 Buffer,並且 byteOffset 小於 buf.length,則將返回 byteOffset。如果 value 為空並且 byteOffset 至少為 buf.length,則將返回 buf.length。
buf.keys()#
- 返回:<Iterator>
建立並返回一個 buf 鍵(索引)的迭代器。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
for (const key of buf.keys()) {
console.log(key);
}
// Prints:
// 0
// 1
// 2
// 3
// 4
// 5const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
for (const key of buf.keys()) {
console.log(key);
}
// Prints:
// 0
// 1
// 2
// 3
// 4
// 5
buf.lastIndexOf(value[, byteOffset][, encoding])#
value<string> | <Buffer> | <Uint8Array> | <integer> 要搜尋的內容。byteOffset<integer> 在buf中開始搜尋的位置。如果為負數,則偏移量從buf的末尾計算。預設值:buf.length - 1。encoding<string> 如果value是一個字串,這是用於確定將在buf中搜索的字串的二進位制表示的編碼。預設值:'utf8'。- 返回:<integer>
buf中最後一次出現value的索引,如果buf不包含value,則返回-1。
與 buf.indexOf() 相同,只是找到的是 value 的最後一次出現,而不是第一次出現。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this buffer is a buffer');
console.log(buf.lastIndexOf('this'));
// Prints: 0
console.log(buf.lastIndexOf('buffer'));
// Prints: 17
console.log(buf.lastIndexOf(Buffer.from('buffer')));
// Prints: 17
console.log(buf.lastIndexOf(97));
// Prints: 15 (97 is the decimal ASCII value for 'a')
console.log(buf.lastIndexOf(Buffer.from('yolo')));
// Prints: -1
console.log(buf.lastIndexOf('buffer', 5));
// Prints: 5
console.log(buf.lastIndexOf('buffer', 4));
// Prints: -1
const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
// Prints: 6
console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
// Prints: 4const { Buffer } = require('node:buffer');
const buf = Buffer.from('this buffer is a buffer');
console.log(buf.lastIndexOf('this'));
// Prints: 0
console.log(buf.lastIndexOf('buffer'));
// Prints: 17
console.log(buf.lastIndexOf(Buffer.from('buffer')));
// Prints: 17
console.log(buf.lastIndexOf(97));
// Prints: 15 (97 is the decimal ASCII value for 'a')
console.log(buf.lastIndexOf(Buffer.from('yolo')));
// Prints: -1
console.log(buf.lastIndexOf('buffer', 5));
// Prints: 5
console.log(buf.lastIndexOf('buffer', 4));
// Prints: -1
const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
// Prints: 6
console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
// Prints: 4
如果 value 不是字串、數字或 Buffer,此方法將丟擲 TypeError。如果 value 是一個數字,它將被強制轉換為一個有效的位元組值,即 0 到 255 之間的整數。
如果 byteOffset 不是一個數字,它將被強制轉換為一個數字。任何強制轉換為 NaN 的引數,如 {} 或 undefined,都會搜尋整個緩衝區。此行為與 String.prototype.lastIndexOf() 匹配。
import { Buffer } from 'node:buffer';
const b = Buffer.from('abcdef');
// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.lastIndexOf(99.9));
console.log(b.lastIndexOf(256 + 99));
// Passing a byteOffset that coerces to NaN.
// Prints: 1, searching the whole buffer.
console.log(b.lastIndexOf('b', undefined));
console.log(b.lastIndexOf('b', {}));
// Passing a byteOffset that coerces to 0.
// Prints: -1, equivalent to passing 0.
console.log(b.lastIndexOf('b', null));
console.log(b.lastIndexOf('b', []));const { Buffer } = require('node:buffer');
const b = Buffer.from('abcdef');
// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.lastIndexOf(99.9));
console.log(b.lastIndexOf(256 + 99));
// Passing a byteOffset that coerces to NaN.
// Prints: 1, searching the whole buffer.
console.log(b.lastIndexOf('b', undefined));
console.log(b.lastIndexOf('b', {}));
// Passing a byteOffset that coerces to 0.
// Prints: -1, equivalent to passing 0.
console.log(b.lastIndexOf('b', null));
console.log(b.lastIndexOf('b', []));
如果 value 是一個空字串或空 Buffer,將返回 byteOffset。
buf.length#
- 型別:<integer>
返回 buf 中的位元組數。
import { Buffer } from 'node:buffer';
// Create a `Buffer` and write a shorter string to it using UTF-8.
const buf = Buffer.alloc(1234);
console.log(buf.length);
// Prints: 1234
buf.write('some string', 0, 'utf8');
console.log(buf.length);
// Prints: 1234const { Buffer } = require('node:buffer');
// Create a `Buffer` and write a shorter string to it using UTF-8.
const buf = Buffer.alloc(1234);
console.log(buf.length);
// Prints: 1234
buf.write('some string', 0, 'utf8');
console.log(buf.length);
// Prints: 1234
buf.readBigUInt64BE([offset])#
從 buf 的指定 offset 處讀取一個無符號、大端序的 64 位整數。
此函式也以 readBigUint64BE 別名提供。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
console.log(buf.readBigUInt64BE(0));
// Prints: 4294967295nconst { Buffer } = require('node:buffer');
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
console.log(buf.readBigUInt64BE(0));
// Prints: 4294967295n
buf.readBigUInt64LE([offset])#
從 buf 的指定 offset 處讀取一個無符號、小端序的 64 位整數。
此函式也以 readBigUint64LE 別名提供。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
console.log(buf.readBigUInt64LE(0));
// Prints: 18446744069414584320nconst { Buffer } = require('node:buffer');
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
console.log(buf.readBigUInt64LE(0));
// Prints: 18446744069414584320n
buf.readDoubleBE([offset])#
從 buf 的指定 offset 處讀取一個 64 位、大端序的雙精度浮點數。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readDoubleBE(0));
// Prints: 8.20788039913184e-304const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readDoubleBE(0));
// Prints: 8.20788039913184e-304
buf.readDoubleLE([offset])#
從 buf 的指定 offset 處讀取一個 64 位、小端序的雙精度浮點數。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readDoubleLE(0));
// Prints: 5.447603722011605e-270
console.log(buf.readDoubleLE(1));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readDoubleLE(0));
// Prints: 5.447603722011605e-270
console.log(buf.readDoubleLE(1));
// Throws ERR_OUT_OF_RANGE.
buf.readFloatBE([offset])#
從 buf 的指定 offset 處讀取一個 32 位、大端序的浮點數。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4]);
console.log(buf.readFloatBE(0));
// Prints: 2.387939260590663e-38const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3, 4]);
console.log(buf.readFloatBE(0));
// Prints: 2.387939260590663e-38
buf.readFloatLE([offset])#
從 buf 的指定 offset 處讀取一個 32 位、小端序的浮點數。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4]);
console.log(buf.readFloatLE(0));
// Prints: 1.539989614439558e-36
console.log(buf.readFloatLE(1));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3, 4]);
console.log(buf.readFloatLE(0));
// Prints: 1.539989614439558e-36
console.log(buf.readFloatLE(1));
// Throws ERR_OUT_OF_RANGE.
buf.readInt8([offset])#
從 buf 的指定 offset 處讀取一個有符號的 8 位整數。
從 Buffer 中讀取的整數被解釋為二進位制補碼有符號值。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([-1, 5]);
console.log(buf.readInt8(0));
// Prints: -1
console.log(buf.readInt8(1));
// Prints: 5
console.log(buf.readInt8(2));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([-1, 5]);
console.log(buf.readInt8(0));
// Prints: -1
console.log(buf.readInt8(1));
// Prints: 5
console.log(buf.readInt8(2));
// Throws ERR_OUT_OF_RANGE.
buf.readInt16BE([offset])#
從 buf 的指定 offset 處讀取一個有符號、大端序的 16 位整數。
從 Buffer 中讀取的整數被解釋為二進位制補碼有符號值。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 5]);
console.log(buf.readInt16BE(0));
// Prints: 5const { Buffer } = require('node:buffer');
const buf = Buffer.from([0, 5]);
console.log(buf.readInt16BE(0));
// Prints: 5
buf.readInt16LE([offset])#
從 buf 的指定 offset 處讀取一個有符號、小端序的 16 位整數。
從 Buffer 中讀取的整數被解釋為二進位制補碼有符號值。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 5]);
console.log(buf.readInt16LE(0));
// Prints: 1280
console.log(buf.readInt16LE(1));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([0, 5]);
console.log(buf.readInt16LE(0));
// Prints: 1280
console.log(buf.readInt16LE(1));
// Throws ERR_OUT_OF_RANGE.
buf.readInt32BE([offset])#
從 buf 的指定 offset 處讀取一個有符號、大端序的 32 位整數。
從 Buffer 中讀取的整數被解釋為二進位制補碼有符號值。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 0, 0, 5]);
console.log(buf.readInt32BE(0));
// Prints: 5const { Buffer } = require('node:buffer');
const buf = Buffer.from([0, 0, 0, 5]);
console.log(buf.readInt32BE(0));
// Prints: 5
buf.readInt32LE([offset])#
從 buf 的指定 offset 處讀取一個有符號、小端序的 32 位整數。
從 Buffer 中讀取的整數被解釋為二進位制補碼有符號值。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 0, 0, 5]);
console.log(buf.readInt32LE(0));
// Prints: 83886080
console.log(buf.readInt32LE(1));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([0, 0, 0, 5]);
console.log(buf.readInt32LE(0));
// Prints: 83886080
console.log(buf.readInt32LE(1));
// Throws ERR_OUT_OF_RANGE.
buf.readIntBE(offset, byteLength)#
offset<integer> 開始讀取前要跳過的位元組數。必須滿足0 <= offset <= buf.length - byteLength。byteLength<integer> 要讀取的位元組數。必須滿足0 < byteLength <= 6。- 返回:<integer>
從 buf 的指定 offset 處讀取 byteLength 個位元組,並將結果解釋為大端序、二進位制補碼的有符號值,支援高達 48 位的精度。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readIntBE(0, 6).toString(16));
// Prints: 1234567890ab
console.log(buf.readIntBE(1, 6).toString(16));
// Throws ERR_OUT_OF_RANGE.
console.log(buf.readIntBE(1, 0).toString(16));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readIntBE(0, 6).toString(16));
// Prints: 1234567890ab
console.log(buf.readIntBE(1, 6).toString(16));
// Throws ERR_OUT_OF_RANGE.
console.log(buf.readIntBE(1, 0).toString(16));
// Throws ERR_OUT_OF_RANGE.
buf.readIntLE(offset, byteLength)#
offset<integer> 開始讀取前要跳過的位元組數。必須滿足0 <= offset <= buf.length - byteLength。byteLength<integer> 要讀取的位元組數。必須滿足0 < byteLength <= 6。- 返回:<integer>
從 buf 的指定 offset 處讀取 byteLength 個位元組,並將結果解釋為小端序、二進位制補碼的有符號值,支援高達 48 位的精度。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readIntLE(0, 6).toString(16));
// Prints: -546f87a9cbeeconst { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readIntLE(0, 6).toString(16));
// Prints: -546f87a9cbee
buf.readUInt8([offset])#
從 buf 的指定 offset 處讀取一個無符號 8 位整數。
此函式也以 readUint8 別名提供。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, -2]);
console.log(buf.readUInt8(0));
// Prints: 1
console.log(buf.readUInt8(1));
// Prints: 254
console.log(buf.readUInt8(2));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, -2]);
console.log(buf.readUInt8(0));
// Prints: 1
console.log(buf.readUInt8(1));
// Prints: 254
console.log(buf.readUInt8(2));
// Throws ERR_OUT_OF_RANGE.
buf.readUInt16BE([offset])#
從 buf 的指定 offset 處讀取一個無符號、大端序的 16 位整數。
此函式也以 readUint16BE 別名提供。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56]);
console.log(buf.readUInt16BE(0).toString(16));
// Prints: 1234
console.log(buf.readUInt16BE(1).toString(16));
// Prints: 3456const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56]);
console.log(buf.readUInt16BE(0).toString(16));
// Prints: 1234
console.log(buf.readUInt16BE(1).toString(16));
// Prints: 3456
buf.readUInt16LE([offset])#
從 buf 的指定 offset 處讀取一個無符號、小端序的 16 位整數。
此函式也以 readUint16LE 別名提供。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56]);
console.log(buf.readUInt16LE(0).toString(16));
// Prints: 3412
console.log(buf.readUInt16LE(1).toString(16));
// Prints: 5634
console.log(buf.readUInt16LE(2).toString(16));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56]);
console.log(buf.readUInt16LE(0).toString(16));
// Prints: 3412
console.log(buf.readUInt16LE(1).toString(16));
// Prints: 5634
console.log(buf.readUInt16LE(2).toString(16));
// Throws ERR_OUT_OF_RANGE.
buf.readUInt32BE([offset])#
從 buf 的指定 offset 處讀取一個無符號、大端序的 32 位整數。
此函式也以 readUint32BE 別名提供。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
console.log(buf.readUInt32BE(0).toString(16));
// Prints: 12345678const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
console.log(buf.readUInt32BE(0).toString(16));
// Prints: 12345678
buf.readUInt32LE([offset])#
從 buf 的指定 offset 處讀取一個無符號、小端序的 32 位整數。
此函式也以 readUint32LE 別名提供。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
console.log(buf.readUInt32LE(0).toString(16));
// Prints: 78563412
console.log(buf.readUInt32LE(1).toString(16));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
console.log(buf.readUInt32LE(0).toString(16));
// Prints: 78563412
console.log(buf.readUInt32LE(1).toString(16));
// Throws ERR_OUT_OF_RANGE.
buf.readUIntBE(offset, byteLength)#
offset<integer> 開始讀取前要跳過的位元組數。必須滿足0 <= offset <= buf.length - byteLength。byteLength<integer> 要讀取的位元組數。必須滿足0 < byteLength <= 6。- 返回:<integer>
從 buf 的指定 offset 處讀取 byteLength 個位元組,並將結果解釋為支援高達 48 位精度的無符號大端序整數。
此函式也以 readUintBE 別名提供。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readUIntBE(0, 6).toString(16));
// Prints: 1234567890ab
console.log(buf.readUIntBE(1, 6).toString(16));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readUIntBE(0, 6).toString(16));
// Prints: 1234567890ab
console.log(buf.readUIntBE(1, 6).toString(16));
// Throws ERR_OUT_OF_RANGE.
buf.readUIntLE(offset, byteLength)#
offset<integer> 開始讀取前要跳過的位元組數。必須滿足0 <= offset <= buf.length - byteLength。byteLength<integer> 要讀取的位元組數。必須滿足0 < byteLength <= 6。- 返回:<integer>
從 buf 的指定 offset 處讀取 byteLength 個位元組,並將結果解釋為支援高達 48 位精度的無符號小端序整數。
此函式也以 readUintLE 別名提供。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readUIntLE(0, 6).toString(16));
// Prints: ab9078563412const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readUIntLE(0, 6).toString(16));
// Prints: ab9078563412
buf.subarray([start[, end]])#
start<integer> 新Buffer的起始位置。預設值:0。end<integer> 新Buffer的結束位置(不包括)。預設值:buf.length。- 返回:<Buffer>
返回一個新的 Buffer,它引用與原始緩衝區相同的記憶體,但透過 start 和 end 索引進行了偏移和裁剪。
指定 end 大於 buf.length 將返回與 end 等於 buf.length 相同的結果。
此方法繼承自 TypedArray.prototype.subarray()。
修改新的 Buffer 切片將會修改原始 Buffer 中的記憶體,因為這兩個物件的已分配記憶體是重疊的。
import { Buffer } from 'node:buffer';
// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
// from the original `Buffer`.
const buf1 = Buffer.allocUnsafe(26);
for (let i = 0; i < 26; i++) {
// 97 is the decimal ASCII value for 'a'.
buf1[i] = i + 97;
}
const buf2 = buf1.subarray(0, 3);
console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: abc
buf1[0] = 33;
console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: !bcconst { Buffer } = require('node:buffer');
// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
// from the original `Buffer`.
const buf1 = Buffer.allocUnsafe(26);
for (let i = 0; i < 26; i++) {
// 97 is the decimal ASCII value for 'a'.
buf1[i] = i + 97;
}
const buf2 = buf1.subarray(0, 3);
console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: abc
buf1[0] = 33;
console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: !bc
指定負數索引會導致切片相對於 buf 的末尾而不是開頭生成。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
console.log(buf.subarray(-6, -1).toString());
// Prints: buffe
// (Equivalent to buf.subarray(0, 5).)
console.log(buf.subarray(-6, -2).toString());
// Prints: buff
// (Equivalent to buf.subarray(0, 4).)
console.log(buf.subarray(-5, -2).toString());
// Prints: uff
// (Equivalent to buf.subarray(1, 4).)const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
console.log(buf.subarray(-6, -1).toString());
// Prints: buffe
// (Equivalent to buf.subarray(0, 5).)
console.log(buf.subarray(-6, -2).toString());
// Prints: buff
// (Equivalent to buf.subarray(0, 4).)
console.log(buf.subarray(-5, -2).toString());
// Prints: uff
// (Equivalent to buf.subarray(1, 4).)
buf.slice([start[, end]])#
start<integer> 新Buffer的起始位置。預設值:0。end<integer> 新Buffer的結束位置(不包括)。預設值:buf.length。- 返回:<Buffer>
buf.subarray。返回一個新的 Buffer,它引用與原始緩衝區相同的記憶體,但透過 start 和 end 索引進行了偏移和裁剪。
此方法與 Buffer 的超類 Uint8Array.prototype.slice() 不相容。要複製切片,請使用 Uint8Array.prototype.slice()。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
const copiedBuf = Uint8Array.prototype.slice.call(buf);
copiedBuf[0]++;
console.log(copiedBuf.toString());
// Prints: cuffer
console.log(buf.toString());
// Prints: buffer
// With buf.slice(), the original buffer is modified.
const notReallyCopiedBuf = buf.slice();
notReallyCopiedBuf[0]++;
console.log(notReallyCopiedBuf.toString());
// Prints: cuffer
console.log(buf.toString());
// Also prints: cuffer (!)const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
const copiedBuf = Uint8Array.prototype.slice.call(buf);
copiedBuf[0]++;
console.log(copiedBuf.toString());
// Prints: cuffer
console.log(buf.toString());
// Prints: buffer
// With buf.slice(), the original buffer is modified.
const notReallyCopiedBuf = buf.slice();
notReallyCopiedBuf[0]++;
console.log(notReallyCopiedBuf.toString());
// Prints: cuffer
console.log(buf.toString());
// Also prints: cuffer (!)
buf.swap16()#
- 返回:<Buffer> 對
buf的引用。
將 buf 解釋為無符號16位整數陣列,並就地交換位元組序。如果 buf.length 不是2的倍數,則丟擲 ERR_INVALID_BUFFER_SIZE。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>
buf1.swap16();
console.log(buf1);
// Prints: <Buffer 02 01 04 03 06 05 08 07>
const buf2 = Buffer.from([0x1, 0x2, 0x3]);
buf2.swap16();
// Throws ERR_INVALID_BUFFER_SIZE.const { Buffer } = require('node:buffer');
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>
buf1.swap16();
console.log(buf1);
// Prints: <Buffer 02 01 04 03 06 05 08 07>
const buf2 = Buffer.from([0x1, 0x2, 0x3]);
buf2.swap16();
// Throws ERR_INVALID_BUFFER_SIZE.
buf.swap16() 的一個便捷用途是執行 UTF-16 小端序和 UTF-16 大端序之間的快速就地轉換。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
buf.swap16(); // Convert to big-endian UTF-16 text.const { Buffer } = require('node:buffer');
const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
buf.swap16(); // Convert to big-endian UTF-16 text.
buf.swap32()#
- 返回:<Buffer> 對
buf的引用。
將 buf 解釋為無符號32位整數陣列,並就地交換位元組序。如果 buf.length 不是4的倍數,則丟擲 ERR_INVALID_BUFFER_SIZE。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>
buf1.swap32();
console.log(buf1);
// Prints: <Buffer 04 03 02 01 08 07 06 05>
const buf2 = Buffer.from([0x1, 0x2, 0x3]);
buf2.swap32();
// Throws ERR_INVALID_BUFFER_SIZE.const { Buffer } = require('node:buffer');
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>
buf1.swap32();
console.log(buf1);
// Prints: <Buffer 04 03 02 01 08 07 06 05>
const buf2 = Buffer.from([0x1, 0x2, 0x3]);
buf2.swap32();
// Throws ERR_INVALID_BUFFER_SIZE.
buf.swap64()#
- 返回:<Buffer> 對
buf的引用。
將 buf 解釋為64位數字陣列,並就地交換位元組序。如果 buf.length 不是8的倍數,則丟擲 ERR_INVALID_BUFFER_SIZE。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>
buf1.swap64();
console.log(buf1);
// Prints: <Buffer 08 07 06 05 04 03 02 01>
const buf2 = Buffer.from([0x1, 0x2, 0x3]);
buf2.swap64();
// Throws ERR_INVALID_BUFFER_SIZE.const { Buffer } = require('node:buffer');
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>
buf1.swap64();
console.log(buf1);
// Prints: <Buffer 08 07 06 05 04 03 02 01>
const buf2 = Buffer.from([0x1, 0x2, 0x3]);
buf2.swap64();
// Throws ERR_INVALID_BUFFER_SIZE.
buf.toJSON()#
- 返回:<Object>
返回 buf 的 JSON 表示。當字串化一個 Buffer 例項時,JSON.stringify() 會隱式呼叫此函式。
Buffer.from() 接受此方法返回格式的物件。特別是,Buffer.from(buf.toJSON()) 的作用類似於 Buffer.from(buf)。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
const json = JSON.stringify(buf);
console.log(json);
// Prints: {"type":"Buffer","data":[1,2,3,4,5]}
const copy = JSON.parse(json, (key, value) => {
return value && value.type === 'Buffer' ?
Buffer.from(value) :
value;
});
console.log(copy);
// Prints: <Buffer 01 02 03 04 05>const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
const json = JSON.stringify(buf);
console.log(json);
// Prints: {"type":"Buffer","data":[1,2,3,4,5]}
const copy = JSON.parse(json, (key, value) => {
return value && value.type === 'Buffer' ?
Buffer.from(value) :
value;
});
console.log(copy);
// Prints: <Buffer 01 02 03 04 05>
buf.toString([encoding[, start[, end]]])#
encoding<string> 要使用的字元編碼。預設值:'utf8'。start<integer> 開始解碼的位元組偏移量。預設值:0。end<integer> 停止解碼的位元組偏移量(不包含)。預設值:buf.length。- 返回: <string>
根據 encoding 中指定的字元編碼將 buf 解碼為字串。可以傳遞 start 和 end 來僅解碼 buf 的一個子集。
如果 encoding 是 'utf8' 並且輸入中的位元組序列不是有效的 UTF-8,那麼每個無效位元組都將被替換為替換字元 U+FFFD。
字串例項的最大長度(以 UTF-16 程式碼單元為單位)可透過 buffer.constants.MAX_STRING_LENGTH 獲取。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.allocUnsafe(26);
for (let i = 0; i < 26; i++) {
// 97 is the decimal ASCII value for 'a'.
buf1[i] = i + 97;
}
console.log(buf1.toString('utf8'));
// Prints: abcdefghijklmnopqrstuvwxyz
console.log(buf1.toString('utf8', 0, 5));
// Prints: abcde
const buf2 = Buffer.from('tést');
console.log(buf2.toString('hex'));
// Prints: 74c3a97374
console.log(buf2.toString('utf8', 0, 3));
// Prints: té
console.log(buf2.toString(undefined, 0, 3));
// Prints: téconst { Buffer } = require('node:buffer');
const buf1 = Buffer.allocUnsafe(26);
for (let i = 0; i < 26; i++) {
// 97 is the decimal ASCII value for 'a'.
buf1[i] = i + 97;
}
console.log(buf1.toString('utf8'));
// Prints: abcdefghijklmnopqrstuvwxyz
console.log(buf1.toString('utf8', 0, 5));
// Prints: abcde
const buf2 = Buffer.from('tést');
console.log(buf2.toString('hex'));
// Prints: 74c3a97374
console.log(buf2.toString('utf8', 0, 3));
// Prints: té
console.log(buf2.toString(undefined, 0, 3));
// Prints: té
buf.values()#
- 返回:<Iterator>
建立並返回一個用於 buf 值(位元組)的迭代器。當在 for..of 語句中使用 Buffer 時,此函式會自動被呼叫。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
for (const value of buf.values()) {
console.log(value);
}
// Prints:
// 98
// 117
// 102
// 102
// 101
// 114
for (const value of buf) {
console.log(value);
}
// Prints:
// 98
// 117
// 102
// 102
// 101
// 114const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
for (const value of buf.values()) {
console.log(value);
}
// Prints:
// 98
// 117
// 102
// 102
// 101
// 114
for (const value of buf) {
console.log(value);
}
// Prints:
// 98
// 117
// 102
// 102
// 101
// 114
buf.write(string[, offset[, length]][, encoding])#
string<string> 要寫入buf的字串。offset<integer> 在開始寫入string之前跳過的位元組數。預設值:0。length<integer> 要寫入的最大位元組數(寫入的位元組數不會超過buf.length - offset)。預設值:buf.length - offset。encoding<string>string的字元編碼。預設值:'utf8'。- 返回:<integer> 寫入的位元組數。
根據 encoding 中的字元編碼,在 offset 位置將 string 寫入 buf。length 引數是要寫入的位元組數。如果 buf 沒有足夠的空間來容納整個字串,則只會寫入 string 的一部分。但是,不會寫入部分編碼的字元。
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(256);
const len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
// Prints: 12 bytes: ½ + ¼ = ¾
const buffer = Buffer.alloc(10);
const length = buffer.write('abcd', 8);
console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
// Prints: 2 bytes : abconst { Buffer } = require('node:buffer');
const buf = Buffer.alloc(256);
const len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
// Prints: 12 bytes: ½ + ¼ = ¾
const buffer = Buffer.alloc(10);
const length = buffer.write('abcd', 8);
console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
// Prints: 2 bytes : ab
buf.writeBigInt64BE(value[, offset])#
value<bigint> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足:0 <= offset <= buf.length - 8。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以大端序將 value 寫入到 buf 中指定的 offset 位置。
value 被解釋並作為二進位制補碼有符號整數寫入。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
buf.writeBigInt64BE(0x0102030405060708n, 0);
console.log(buf);
// Prints: <Buffer 01 02 03 04 05 06 07 08>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
buf.writeBigInt64BE(0x0102030405060708n, 0);
console.log(buf);
// Prints: <Buffer 01 02 03 04 05 06 07 08>
buf.writeBigInt64LE(value[, offset])#
value<bigint> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足:0 <= offset <= buf.length - 8。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以小端序將 value 寫入到 buf 中指定的 offset 位置。
value 被解釋並作為二進位制補碼有符號整數寫入。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
buf.writeBigInt64LE(0x0102030405060708n, 0);
console.log(buf);
// Prints: <Buffer 08 07 06 05 04 03 02 01>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
buf.writeBigInt64LE(0x0102030405060708n, 0);
console.log(buf);
// Prints: <Buffer 08 07 06 05 04 03 02 01>
buf.writeBigUInt64BE(value[, offset])#
value<bigint> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足:0 <= offset <= buf.length - 8。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以大端序將 value 寫入到 buf 中指定的 offset 位置。
此函式也可透過別名 writeBigUint64BE 使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
console.log(buf);
// Prints: <Buffer de ca fa fe ca ce fa de>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
console.log(buf);
// Prints: <Buffer de ca fa fe ca ce fa de>
buf.writeBigUInt64LE(value[, offset])#
value<bigint> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足:0 <= offset <= buf.length - 8。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以小端序將 value 寫入到 buf 中指定的 offset 位置。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
console.log(buf);
// Prints: <Buffer de fa ce ca fe fa ca de>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
console.log(buf);
// Prints: <Buffer de fa ce ca fe fa ca de>
此函式也可透過別名 writeBigUint64LE 使用。
buf.writeDoubleBE(value[, offset])#
value<number> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - 8。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以大端序將 value 寫入到 buf 中指定的 offset 位置。value 必須是 JavaScript 數字。當 value 不是 JavaScript 數字時,行為未定義。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
buf.writeDoubleBE(123.456, 0);
console.log(buf);
// Prints: <Buffer 40 5e dd 2f 1a 9f be 77>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
buf.writeDoubleBE(123.456, 0);
console.log(buf);
// Prints: <Buffer 40 5e dd 2f 1a 9f be 77>
buf.writeDoubleLE(value[, offset])#
value<number> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - 8。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以小端序將 value 寫入到 buf 中指定的 offset 位置。value 必須是 JavaScript 數字。當 value 不是 JavaScript 數字時,行為未定義。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
buf.writeDoubleLE(123.456, 0);
console.log(buf);
// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
buf.writeDoubleLE(123.456, 0);
console.log(buf);
// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>
buf.writeFloatBE(value[, offset])#
value<number> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - 4。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以大端序將 value 寫入到 buf 中指定的 offset 位置。當 value 不是 JavaScript 數字時,行為未定義。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeFloatBE(0xcafebabe, 0);
console.log(buf);
// Prints: <Buffer 4f 4a fe bb>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeFloatBE(0xcafebabe, 0);
console.log(buf);
// Prints: <Buffer 4f 4a fe bb>
buf.writeFloatLE(value[, offset])#
value<number> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - 4。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以小端序將 value 寫入到 buf 中指定的 offset 位置。當 value 不是 JavaScript 數字時,行為未定義。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeFloatLE(0xcafebabe, 0);
console.log(buf);
// Prints: <Buffer bb fe 4a 4f>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeFloatLE(0xcafebabe, 0);
console.log(buf);
// Prints: <Buffer bb fe 4a 4f>
buf.writeInt8(value[, offset])#
value<integer> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - 1。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
將 value 寫入到 buf 中指定的 offset 位置。value 必須是有效的有符號8位整數。當 value 不是有符號8位整數時,行為未定義。
value 被解釋並作為二進位制補碼有符號整數寫入。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
buf.writeInt8(2, 0);
buf.writeInt8(-2, 1);
console.log(buf);
// Prints: <Buffer 02 fe>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
buf.writeInt8(2, 0);
buf.writeInt8(-2, 1);
console.log(buf);
// Prints: <Buffer 02 fe>
buf.writeInt16BE(value[, offset])#
value<integer> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - 2。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以大端序將 value 寫入到 buf 中指定的 offset 位置。value 必須是有效的有符號16位整數。當 value 不是有符號16位整數時,行為未定義。
value 被解釋並作為二進位制補碼有符號整數寫入。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
buf.writeInt16BE(0x0102, 0);
console.log(buf);
// Prints: <Buffer 01 02>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
buf.writeInt16BE(0x0102, 0);
console.log(buf);
// Prints: <Buffer 01 02>
buf.writeInt16LE(value[, offset])#
value<integer> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - 2。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以小端序將 value 寫入到 buf 中指定的 offset 位置。value 必須是有效的有符號16位整數。當 value 不是有符號16位整數時,行為未定義。
value 被解釋並作為二進位制補碼有符號整數寫入。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
buf.writeInt16LE(0x0304, 0);
console.log(buf);
// Prints: <Buffer 04 03>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
buf.writeInt16LE(0x0304, 0);
console.log(buf);
// Prints: <Buffer 04 03>
buf.writeInt32BE(value[, offset])#
value<integer> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - 4。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以大端序將 value 寫入到 buf 中指定的 offset 位置。value 必須是有效的有符號32位整數。當 value 不是有符號32位整數時,行為未定義。
value 被解釋並作為二進位制補碼有符號整數寫入。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeInt32BE(0x01020304, 0);
console.log(buf);
// Prints: <Buffer 01 02 03 04>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeInt32BE(0x01020304, 0);
console.log(buf);
// Prints: <Buffer 01 02 03 04>
buf.writeInt32LE(value[, offset])#
value<integer> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - 4。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以小端序將 value 寫入到 buf 中指定的 offset 位置。value 必須是有效的有符號32位整數。當 value 不是有符號32位整數時,行為未定義。
value 被解釋並作為二進位制補碼有符號整數寫入。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeInt32LE(0x05060708, 0);
console.log(buf);
// Prints: <Buffer 08 07 06 05>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeInt32LE(0x05060708, 0);
console.log(buf);
// Prints: <Buffer 08 07 06 05>
buf.writeIntBE(value, offset, byteLength)#
value<integer> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - byteLength。byteLength<integer> 要寫入的位元組數。必須滿足0 < byteLength <= 6。- 返回:<integer>
offset加上寫入的位元組數。
以大端序將 value 的 byteLength 位元組寫入到 buf 中指定的 offset 位置。支援高達48位的精度。當 value 不是有符號整數時,行為未定義。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
buf.writeIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer 12 34 56 78 90 ab>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
buf.writeIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer 12 34 56 78 90 ab>
buf.writeIntLE(value, offset, byteLength)#
value<integer> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - byteLength。byteLength<integer> 要寫入的位元組數。必須滿足0 < byteLength <= 6。- 返回:<integer>
offset加上寫入的位元組數。
以小端序將 value 的 byteLength 位元組寫入到 buf 中指定的 offset 位置。支援高達48位的精度。當 value 不是有符號整數時,行為未定義。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
buf.writeIntLE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer ab 90 78 56 34 12>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
buf.writeIntLE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer ab 90 78 56 34 12>
buf.writeUInt8(value[, offset])#
value<integer> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - 1。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
將 value 寫入到 buf 中指定的 offset 位置。value 必須是有效的無符號8位整數。當 value 不是無符號8位整數時,行為未定義。
此函式也可透過別名 writeUint8 使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeUInt8(0x3, 0);
buf.writeUInt8(0x4, 1);
buf.writeUInt8(0x23, 2);
buf.writeUInt8(0x42, 3);
console.log(buf);
// Prints: <Buffer 03 04 23 42>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeUInt8(0x3, 0);
buf.writeUInt8(0x4, 1);
buf.writeUInt8(0x23, 2);
buf.writeUInt8(0x42, 3);
console.log(buf);
// Prints: <Buffer 03 04 23 42>
buf.writeUInt16BE(value[, offset])#
value<integer> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - 2。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以大端序將 value 寫入到 buf 中指定的 offset 位置。value 必須是有效的無符號16位整數。當 value 不是無符號16位整數時,行為未定義。
此函式也可透過別名 writeUint16BE 使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeUInt16BE(0xdead, 0);
buf.writeUInt16BE(0xbeef, 2);
console.log(buf);
// Prints: <Buffer de ad be ef>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeUInt16BE(0xdead, 0);
buf.writeUInt16BE(0xbeef, 2);
console.log(buf);
// Prints: <Buffer de ad be ef>
buf.writeUInt16LE(value[, offset])#
value<integer> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - 2。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以小端序將 value 寫入到 buf 中指定的 offset 位置。value 必須是有效的無符號16位整數。當 value 不是無符號16位整數時,行為未定義。
此函式也可透過別名 writeUint16LE 使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeUInt16LE(0xdead, 0);
buf.writeUInt16LE(0xbeef, 2);
console.log(buf);
// Prints: <Buffer ad de ef be>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeUInt16LE(0xdead, 0);
buf.writeUInt16LE(0xbeef, 2);
console.log(buf);
// Prints: <Buffer ad de ef be>
buf.writeUInt32BE(value[, offset])#
value<integer> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - 4。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以大端序將 value 寫入到 buf 中指定的 offset 位置。value 必須是有效的無符號32位整數。當 value 不是無符號32位整數時,行為未定義。
此函式也可透過別名 writeUint32BE 使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeUInt32BE(0xfeedface, 0);
console.log(buf);
// Prints: <Buffer fe ed fa ce>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeUInt32BE(0xfeedface, 0);
console.log(buf);
// Prints: <Buffer fe ed fa ce>
buf.writeUInt32LE(value[, offset])#
value<integer> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - 4。預設值:0。- 返回:<integer>
offset加上寫入的位元組數。
以小端序將 value 寫入到 buf 中指定的 offset 位置。value 必須是有效的無符號32位整數。當 value 不是無符號32位整數時,行為未定義。
此函式也可透過別名 writeUint32LE 使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeUInt32LE(0xfeedface, 0);
console.log(buf);
// Prints: <Buffer ce fa ed fe>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeUInt32LE(0xfeedface, 0);
console.log(buf);
// Prints: <Buffer ce fa ed fe>
buf.writeUIntBE(value, offset, byteLength)#
value<integer> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - byteLength。byteLength<integer> 要寫入的位元組數。必須滿足0 < byteLength <= 6。- 返回:<integer>
offset加上寫入的位元組數。
以大端序將 value 的 byteLength 位元組寫入到 buf 中指定的 offset 位置。支援高達48位的精度。當 value 不是無符號整數時,行為未定義。
此函式也可透過別名 writeUintBE 使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
buf.writeUIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer 12 34 56 78 90 ab>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
buf.writeUIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer 12 34 56 78 90 ab>
buf.writeUIntLE(value, offset, byteLength)#
value<integer> 要寫入buf的數字。offset<integer> 開始寫入前要跳過的位元組數。必須滿足0 <= offset <= buf.length - byteLength。byteLength<integer> 要寫入的位元組數。必須滿足0 < byteLength <= 6。- 返回:<integer>
offset加上寫入的位元組數。
以小端序將 value 的 byteLength 位元組寫入到 buf 中指定的 offset 位置。支援高達48位的精度。當 value 不是無符號整數時,行為未定義。
此函式也可透過別名 writeUintLE 使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
buf.writeUIntLE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer ab 90 78 56 34 12>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
buf.writeUIntLE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer ab 90 78 56 34 12>
new Buffer(arrayBuffer[, byteOffset[, length]])#
arrayBuffer<ArrayBuffer> | <SharedArrayBuffer> 一個 <ArrayBuffer>、<SharedArrayBuffer> 或 <TypedArray> 的.buffer屬性。byteOffset<integer> 要暴露的第一個位元組的索引。預設值:0。length<integer> 要暴露的位元組數。預設值:arrayBuffer.byteLength - byteOffset。
new Buffer(buffer)#
Buffer.from(buffer)。buffer<Buffer> | <Uint8Array> 一個現有的Buffer或 <Uint8Array>,從中複製資料。
new Buffer(size)#
size<integer> 新Buffer的期望長度。
參見 Buffer.alloc() 和 Buffer.allocUnsafe()。此建構函式變體等同於 Buffer.alloc()。
new Buffer(string[, encoding])#
Buffer.from(string[, encoding])。類:File#
- 繼承自:<Blob>
<File> 提供有關檔案的資訊。
new buffer.File(sources, fileName[, options])#
sources<string[]> | <ArrayBuffer[]> | <TypedArray[]> | <DataView[]> | <Blob[]> | <File[]> 一個由字串、<ArrayBuffer>、<TypedArray>、<DataView>、<File> 或 <Blob> 物件組成的陣列,或這些物件的任意混合,它們將被儲存在File中。fileName<string> 檔名。options<Object>
node:buffer 模組 API#
雖然 Buffer 物件可作為全域性物件使用,但還有一些與 Buffer 相關的附加 API 只能透過 node:buffer 模組(使用 require('node:buffer') 訪問)獲得。
buffer.atob(data)#
Buffer.from(data, 'base64')。data<any> Base64 編碼的輸入字串。
將 Base64 編碼的資料字串解碼為位元組,並使用 Latin-1 (ISO-8859-1) 將這些位元組編碼為字串。
data 可以是任何可以被強制轉換為字串的 JavaScript 值。
此函式僅為與舊版 Web 平臺 API 相容而提供,不應在任何新程式碼中使用,因為它們使用字串來表示二進位制資料,並且早於 JavaScript 中引入型別化陣列。對於使用 Node.js API 執行的程式碼,應使用 Buffer.from(str, 'base64') 和 buf.toString('base64') 在 base64 編碼的字串和二進位制資料之間進行轉換。
buffer.btoa(data)#
buf.toString('base64')。data<any> 一個 ASCII (Latin1) 字串。
使用 Latin-1 (ISO-8859) 將字串解碼為位元組,並使用 Base64 將這些位元組編碼為字串。
data 可以是任何可以被強制轉換為字串的 JavaScript 值。
此函式僅為與舊版 Web 平臺 API 相容而提供,不應在任何新程式碼中使用,因為它們使用字串來表示二進位制資料,並且早於 JavaScript 中引入型別化陣列。對於使用 Node.js API 執行的程式碼,應使用 Buffer.from(str, 'base64') 和 buf.toString('base64') 在 base64 編碼的字串和二進位制資料之間進行轉換。
buffer.isAscii(input)#
input<Buffer> | <ArrayBuffer> | <TypedArray> 要驗證的輸入。- 返回:<boolean>
如果 input 僅包含有效的 ASCII 編碼資料,則此函式返回 true,包括 input 為空的情況。
如果 input 是一個已分離的陣列緩衝區,則丟擲錯誤。
buffer.isUtf8(input)#
input<Buffer> | <ArrayBuffer> | <TypedArray> 要驗證的輸入。- 返回:<boolean>
如果 input 僅包含有效的 UTF-8 編碼資料,則此函式返回 true,包括 input 為空的情況。
如果 input 是一個已分離的陣列緩衝區,則丟擲錯誤。
buffer.INSPECT_MAX_BYTES#
- 型別:<integer> 預設值:
50
返回呼叫 buf.inspect() 時將返回的最大位元組數。這可以被使用者模組覆蓋。有關 buf.inspect() 行為的更多詳細資訊,請參見 util.inspect()。
buffer.resolveObjectURL(id)#
將一個 'blob:nodedata:...' 解析為先前透過呼叫 URL.createObjectURL() 註冊的關聯 <Blob> 物件。
buffer.transcode(source, fromEnc, toEnc)#
source<Buffer> | <Uint8Array> 一個Buffer或Uint8Array例項。fromEnc<string> 當前編碼。toEnc<string> 目標編碼。- 返回:<Buffer>
將給定的 Buffer 或 Uint8Array 例項從一種字元編碼重新編碼為另一種。返回一個新的 Buffer 例項。
如果 fromEnc 或 toEnc 指定了無效的字元編碼,或者不允許從 fromEnc 轉換為 toEnc,則丟擲錯誤。
buffer.transcode() 支援的編碼有:'ascii'、'utf8'、'utf16le'、'ucs2'、'latin1' 和 'binary'。
如果給定的位元組序列無法在目標編碼中充分表示,轉碼過程將使用替換字元。例如:
import { Buffer, transcode } from 'node:buffer';
const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
console.log(newBuf.toString('ascii'));
// Prints: '?'const { Buffer, transcode } = require('node:buffer');
const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
console.log(newBuf.toString('ascii'));
// Prints: '?'
因為歐元符號(€)在 US-ASCII 中無法表示,所以在轉碼後的 Buffer 中它被替換為 ?。
Buffer 常量#
buffer.constants.MAX_LENGTH#
- 型別:<integer> 單個
Buffer例項允許的最大大小。
在 32 位架構上,此值當前為 230 - 1(約 1 GiB)。
在 64 位架構上,此值當前為 253 - 1(約 8 PiB)。
它在底層反映了 v8::TypedArray::kMaxLength。
此值也可用作 buffer.kMaxLength。
Buffer.from()、Buffer.alloc() 和 Buffer.allocUnsafe()#
在 6.0.0 之前的 Node.js 版本中,Buffer 例項是使用 Buffer 建構函式建立的,該函式會根據提供的引數以不同方式分配返回的 Buffer。
- 將數字作為第一個引數傳遞給
Buffer()(例如new Buffer(10))會分配一個指定大小的新Buffer物件。在 Node.js 8.0.0 之前,為此類Buffer例項分配的記憶體是未初始化的,並且可能包含敏感資料。此類Buffer例項必須隨後透過使用buf.fill(0)或在從Buffer讀取資料之前寫入整個Buffer來進行初始化。雖然這種行為是有意為了提高效能,但開發經驗表明,在建立快速但未初始化的Buffer和建立較慢但更安全的Buffer之間需要更明確的區分。自 Node.js 8.0.0 起,Buffer(num)和new Buffer(num)返回一個帶有初始化記憶體的Buffer。 - 將字串、陣列或
Buffer作為第一個引數傳遞會將傳遞物件的資料複製到Buffer中。 - 傳遞一個 <ArrayBuffer> 或 <SharedArrayBuffer> 會返回一個與給定陣列緩衝區共享已分配記憶體的
Buffer。
由於 new Buffer() 的行為根據第一個引數的型別而有所不同,因此當未執行引數驗證或 Buffer 初始化時,可能會無意中給應用程式帶來安全性和可靠性問題。
例如,如果攻擊者可以使應用程式在期望字串的地方接收到一個數字,應用程式可能會呼叫 new Buffer(100) 而不是 new Buffer("100"),導致它分配一個 100 位元組的緩衝區,而不是分配一個內容為 "100" 的 3 位元組緩衝區。這通常可以透過 JSON API 呼叫實現。由於 JSON 區分數字和字串型別,它允許在編寫不當且未充分驗證其輸入的應用程式中注入數字,而該應用程式可能期望總是接收到一個字串。在 Node.js 8.0.0 之前,100 位元組的緩衝區可能包含任意已存在的記憶體資料,因此可能被用來向遠端攻擊者暴露記憶體中的秘密。自 Node.js 8.0.0 起,記憶體暴露不會發生,因為資料是零填充的。但是,其他攻擊仍然可能發生,例如導致伺服器分配非常大的緩衝區,從而導致效能下降或因記憶體耗盡而崩潰。
為了使 Buffer 例項的建立更加可靠且不易出錯,各種形式的 new Buffer() 建構函式已被棄用,並由單獨的 Buffer.from()、Buffer.alloc() 和 Buffer.allocUnsafe() 方法取代。
開發者應將所有現有的 new Buffer() 建構函式用法遷移到這些新的 API 之一。
Buffer.from(array)返回一個新的Buffer,其中包含所提供八位位元組的副本。Buffer.from(arrayBuffer[, byteOffset[, length]])返回一個新的Buffer,它與給定的 <ArrayBuffer> 共享相同的已分配記憶體。Buffer.from(buffer)返回一個新的Buffer,其中包含給定Buffer內容的副本。Buffer.from(string[, encoding])返回一個新的Buffer,其中包含所提供字串的副本。Buffer.alloc(size[, fill[, encoding]])返回一個指定大小的新的已初始化Buffer。此方法比Buffer.allocUnsafe(size)慢,但保證新建立的Buffer例項絕不包含可能敏感的舊資料。如果size不是數字,則會丟擲TypeError。Buffer.allocUnsafe(size)和Buffer.allocUnsafeSlow(size)各返回一個指定size的新的未初始化Buffer。因為Buffer是未初始化的,所以分配的記憶體段可能包含可能敏感的舊資料。
由 Buffer.allocUnsafe()、Buffer.from(string)、Buffer.concat() 和 Buffer.from(array) 返回的 Buffer 例項,如果 size 小於或等於 Buffer.poolSize 的一半,可能會從共享的內部記憶體池中分配。由 Buffer.allocUnsafeSlow() 返回的例項從不使用共享的內部記憶體池。
--zero-fill-buffers 命令列選項#
Node.js 可以使用 --zero-fill-buffers 命令列選項啟動,以使所有新分配的 Buffer 例項在建立時預設進行零填充。如果沒有該選項,用 Buffer.allocUnsafe() 和 Buffer.allocUnsafeSlow() 建立的緩衝區不會進行零填充。使用此標誌可能會對效能產生可衡量的負面影響。僅在必要時使用 --zero-fill-buffers 選項,以強制新分配的 Buffer 例項不能包含可能敏感的舊資料。
$ node --zero-fill-buffers
> Buffer.allocUnsafe(5);
<Buffer 00 00 00 00 00>
是什麼讓 Buffer.allocUnsafe() 和 Buffer.allocUnsafeSlow() “不安全”?#
當呼叫 Buffer.allocUnsafe() 和 Buffer.allocUnsafeSlow() 時,分配的記憶體段是未初始化的(它沒有被清零)。雖然這種設計使得記憶體分配非常快,但分配的記憶體段可能包含可能敏感的舊資料。使用由 Buffer.allocUnsafe() 建立的 Buffer 而沒有完全覆蓋記憶體,可能會在讀取 Buffer 記憶體時導致這些舊資料被洩露。
雖然使用 Buffer.allocUnsafe() 有明顯的效能優勢,但必須格外小心,以避免給應用程式引入安全漏洞。