- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- env 环境变量
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
Node.js v22.22.0 文档
- Node.js v22.22.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()
- 缓冲区
-
导航
- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- env 环境变量
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- 其他版本
缓冲区#>
【Buffer】
源代码: lib/buffer.js
Buffer 对象用于表示固定长度的字节序列。许多 Node.js API 支持 Buffer。
Buffer 类是 JavaScript 的 <Uint8Array> 类的一个子类,并通过方法扩展了它,以涵盖更多的使用场景。Node.js 的 API 在支持 Buffer 的地方也接受普通的 <Uint8Array>。
【The Buffer class is a subclass of JavaScript's <Uint8Array> class and
extends it with methods that cover additional use cases. Node.js APIs accept
plain <Uint8Array>s wherever Buffers are supported as well.】
虽然 Buffer 类在全局作用域中可用,但仍然建议通过 import 或 require 语句显式引用它。
【While the Buffer class is available within the global scope, it is still
recommended to explicitly reference it via an import or require statement.】
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');
缓冲区和字符编码#>
【Buffers and character encodings】
在 Buffer 与字符串之间转换时,可以指定字符编码。如果未指定字符编码,将使用 UTF-8 作为默认值。
【When converting between Buffers and strings, a character encoding may be
specified. If no character encoding is specified, UTF-8 will be used as the
default.】
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 buffers accept all case variations of encoding strings that they
receive. For example, UTF-8 can be specified as 'utf8', 'UTF8', or 'uTf8'.】
Node.js 目前支持的字符编码如下:
【The character encodings currently supported by Node.js are the following:】
-
'utf8'(别名:'utf-8'):多字节编码的 Unicode 字符。许多网页和其他文档格式使用 UTF-8。这是默认的字符编码。当将Buffer解码为不完全包含有效 UTF-8 数据的字符串时,将使用 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 称为编码。
【Converting a Buffer into a string using one of the above is referred to as
decoding, and converting a string into a Buffer is referred to as encoding.】
Node.js 还支持以下二进制到文本的编码。对于二进制到文本的编码,命名约定是相反的:将 Buffer 转换为字符串通常称为编码,而将字符串转换为 Buffer 则称为解码。
【Node.js also supports the following binary-to-text encodings. For
binary-to-text encodings, the naming convention is reversed: Converting a
Buffer into a string is typically referred to as encoding, and converting a
string into a Buffer as decoding.】
-
'base64':Base64 编码。从字符串创建Buffer时,这种编码也能正确接受 RFC 4648,第5节 中规定的“URL 和文件名安全字母表”。base64 编码字符串中的空格、制表符和换行符等空白字符将被忽略。 -
'base64url':按照 RFC 4648,第5节 指定的 base64url 编码。当从字符串创建Buffer时,这种编码也可以正确接受常规的 base64 编码字符串。将Buffer编码为字符串时,该编码会省略填充字符。 -
'hex':将每个字节编码为两个十六进制字符。当解码不完全由偶数个十六进制字符组成的字符串时,可能会发生数据截断。示例如下。
还支持以下旧版字符编码:
【The following legacy character encodings are also supported:】
-
'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.
现代网页浏览器遵循 WHATWG 编码标准,该规范将 'latin1' 和 'ISO-8859-1' 都别名为 'win-1252'。这意味着,在执行类似 http.get() 的操作时,如果返回的字符集是 WHATWG 规范中列出的某一种,服务器实际上可能返回的是 'win-1252' 编码的数据,而使用 'latin1' 编码可能会错误地解码这些字符。
【Modern Web browsers follow the WHATWG Encoding Standard which aliases
both 'latin1' and 'ISO-8859-1' to 'win-1252'. This means that while doing
something like http.get(), if the returned charset is one of those listed in
the WHATWG specification it is possible that the server actually returned
'win-1252'-encoded data, and using 'latin1' encoding may incorrectly decode
the characters.】
缓冲区和 TypedArray#>
【Buffers and TypedArrays】
Buffer 实例也是 JavaScript 的 <Uint8Array> 和 <TypedArray> 实例。所有 <TypedArray> 方法在 Buffer 上都可用。然而,Buffer API 与 <TypedArray> API 之间存在一些细微的不兼容性。
特别是:
【In particular:】
- 当
TypedArray.prototype.slice()创建TypedArray部分内容的副本时,Buffer.prototype.slice()则是在现有Buffer上创建一个视图,而不进行复制。这个行为可能令人惊讶,并且仅为了兼容旧版本而存在。TypedArray.prototype.subarray()可以用于在Buffer和其他TypedArray上实现Buffer.prototype.slice()的行为,并且应当优先使用。 buf.toString()与其TypedArray等效方法不兼容。- 一些方法,例如
buf.indexOf(),支持额外的参数。
有两种方法可以从 Buffer 创建新的 <TypedArray> 实例:
【There are two ways to create new <TypedArray> instances from a Buffer:】
- 将
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()。
【It is possible to create a new Buffer that shares the same allocated
memory as a <TypedArray> instance by using the TypedArray object's
.buffer property in the same way. Buffer.from()
behaves like new Uint8Array() in this context.】
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> 的一部分。
【When creating a Buffer using a <TypedArray>'s .buffer, it is
possible to use only a portion of the underlying <ArrayBuffer> by passing in
byteOffset and length parameters.】
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> 变体接受第二个参数,该参数是一个映射函数,会在类型化数组的每个元素上调用:
【The Buffer.from() and TypedArray.from() have different signatures and
implementations. Specifically, the <TypedArray> variants accept a second
argument that is a mapping function that is invoked on every element of the
typed array:】
Buffer.from() 方法不支持使用映射函数:
【The Buffer.from() method, however, does not support the use of a mapping
function:】
缓冲区和迭代#>
【Buffers and iteration】
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() 方法可用于创建迭代器。
【Additionally, the buf.values(), buf.keys(), and
buf.entries() methods can be used to create iterators.】
类:Blob#>
【Class: Blob】
一个 <Blob> 封装了不可变的原始数据,可以安全地在多个工作线程之间共享。
【A <Blob> encapsulates immutable, raw data that can be safely shared across multiple worker threads.】
new buffer.Blob([sources[, options]])#>
sources<string[]> | <ArrayBuffer[]> | <TypedArray[]> | <DataView[]> | <Blob[]> 一个包含字符串、<ArrayBuffer>、<TypedArray>、<DataView> 或 <Blob> 对象的数组,或者这些对象的混合数组,这些内容将被存储到Blob中。options<Object>
创建一个新的 Blob 对象,包含给定来源的拼接内容。
【Creates a new Blob object containing a concatenation of the given sources.】
<ArrayBuffer>、<TypedArray>、<DataView> 和 <Buffer> 源已被复制到“Blob”中,因此在创建“Blob”之后可以安全地修改它们。
字符串源被编码为 UTF-8 字节序列并复制到 Blob 中。每个字符串部分中不匹配的代理对将被替换为 Unicode U+FFFD 替代字符。
【String sources are encoded as UTF-8 byte sequences and copied into the Blob. Unmatched surrogate pairs within each string part will be replaced by Unicode U+FFFD replacement characters.】
blob.arrayBuffer()#>
- 返回: <Promise>
返回一个承诺,该承诺会以包含 Blob 数据副本的 <ArrayBuffer> 作为结果。
【Returns a promise that fulfills with an <ArrayBuffer> containing a copy of
the Blob data.】
blob.bytes()#>
blob.bytes() 方法返回 Blob 对象的字节,作为一个 Promise<Uint8Array>。
【The blob.bytes() method returns the byte of the Blob object as a Promise<Uint8Array>.】
const blob = new Blob(['hello']);
blob.bytes().then((bytes) => {
console.log(bytes); // Outputs: Uint8Array(5) [ 104, 101, 108, 108, 111 ]
});
blob.size#>
Blob 的总字节大小。
【The total size of the Blob in bytes.】
blob.slice([start[, end[, type]]])#>
创建并返回一个包含此 Blob 对象数据子集的新 Blob。原始 Blob 不会被更改。
【Creates and returns a new Blob containing a subset of this Blob objects
data. The original Blob is not altered.】
blob.stream()#>
- 返回: <ReadableStream>
返回一个新的 ReadableStream,允许读取 Blob 的内容。
【Returns a new ReadableStream that allows the content of the Blob to be read.】
blob.text()#>
- 返回: <Promise>
返回一个 Promise,该 Promise 在 Blob 的内容被解码为 UTF-8 字符串后被完成。
【Returns a promise that fulfills with the contents of the Blob decoded as a
UTF-8 string.】
blob.type#>
- 类型: <string>
Blob 的内容类型。
【The content-type of the Blob.】
Blob 对象和 MessageChannel#>
【Blob objects and MessageChannel】
一旦创建了 <Blob> 对象,它可以通过 MessagePort 发送到多个目的地,而无需传输或立即复制数据。Blob 所包含的数据只有在调用 arrayBuffer() 或 text() 方法时才会被复制。
【Once a <Blob> object is created, it can be sent via MessagePort to multiple
destinations without transferring or immediately copying the data. The data
contained by the Blob is copied only when the arrayBuffer() or text()
methods are called.】
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#>
【Class: Buffer】
Buffer 类是一个用于直接处理二进制数据的全局类型。它可以通过多种方式进行构造。
【The Buffer class is a global type for dealing with binary data directly.
It can be constructed in a variety of ways.】
静态方法:Buffer.alloc(size[, fill[, encoding]])#>
【Static method: Buffer.alloc(size[, fill[, encoding]])】
size<integer> 新Buffer的期望长度。fill<string> | <Buffer> | <Uint8Array> | <integer> 用于预填充新Buffer的值。默认值:0。encoding<string> 如果fill是字符串,则这是它的编码方式。默认值:'utf8'。- 返回: <Buffer>
分配一个新的 Buffer,大小为 size 字节。如果 fill 是 undefined,Buffer 将会被填充为零。
【Allocates a new Buffer of size bytes. If fill is undefined, the
Buffer will be zero-filled.】
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。
【If size is larger than
buffer.constants.MAX_LENGTH or smaller than 0, ERR_OUT_OF_RANGE
is thrown.】
如果指定了 fill,分配的 Buffer 将通过调用 buf.fill(fill) 进行初始化。
【If fill is specified, the allocated Buffer will be initialized by calling
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) 来初始化。
【If both fill and encoding are specified, the allocated Buffer will be
initialized by calling 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 分配的数据。
【Calling Buffer.alloc() can be measurably slower than the alternative
Buffer.allocUnsafe() but ensures that the newly created Buffer instance
contents will never contain sensitive data from previous allocations, including
data that might not have been allocated for Buffers.】
如果 size 不是数字,将会抛出 TypeError。
【A TypeError will be thrown if size is not a number.】
静态方法:Buffer.allocUnsafe(size)#>
【Static method: Buffer.allocUnsafe(size)】
分配一个大小为 size 字节的新 Buffer。如果 size 大于 buffer.constants.MAX_LENGTH 或小于 0,将抛出 ERR_OUT_OF_RANGE。
【Allocates a new Buffer of size bytes. If size is larger than
buffer.constants.MAX_LENGTH or smaller than 0, ERR_OUT_OF_RANGE
is thrown.】
以这种方式创建的 Buffer 实例的底层内存未初始化。新创建的 Buffer 的内容未知,可能包含敏感数据。使用 Buffer.alloc() 来初始化 Buffer 实例并填充零值。
【The underlying memory for Buffer instances created in this way is not
initialized. The contents of the newly created Buffer are unknown and
may contain sensitive data. Use Buffer.alloc() instead to initialize
Buffer instances with zeroes.】
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。
【A TypeError will be thrown if size is not a number.】
Buffer 模块预先分配了一个大小为 Buffer.poolSize 的内部 Buffer 实例,该实例用作快速分配新 Buffer 实例的池,这些实例仅在使用 Buffer.allocUnsafe()、Buffer.from(array)、Buffer.from(string) 和 Buffer.concat() 创建时,并且当 size 小于 Buffer.poolSize >>> 1(Buffer.poolSize 除以二的下取整)时才使用。
【The Buffer module pre-allocates an internal Buffer instance of
size Buffer.poolSize that is used as a pool for the fast allocation of new
Buffer instances created using Buffer.allocUnsafe(), Buffer.from(array),
Buffer.from(string), and Buffer.concat() only when size is less than
Buffer.poolSize >>> 1 (floor of Buffer.poolSize divided by two).】
使用这个预分配的内部内存池是调用 Buffer.alloc(size, fill) 与 Buffer.allocUnsafe(size).fill(fill) 之间的关键区别。具体来说,Buffer.alloc(size, fill) 永远不会使用内部的 Buffer 池,而 Buffer.allocUnsafe(size).fill(fill) 如果 size 小于或等于 Buffer.poolSize 的一半,则会使用内部 Buffer 池。这种差异很微妙,但当应用需要 Buffer.allocUnsafe() 提供的额外性能时可能很重要。
【Use of this pre-allocated internal memory pool is a key difference between
calling Buffer.alloc(size, fill) vs. Buffer.allocUnsafe(size).fill(fill).
Specifically, Buffer.alloc(size, fill) will never use the internal Buffer
pool, while Buffer.allocUnsafe(size).fill(fill) will use the internal
Buffer pool if size is less than or equal to half Buffer.poolSize. The
difference is subtle but can be important when an application requires the
additional performance that Buffer.allocUnsafe() provides.】
静态方法:Buffer.allocUnsafeSlow(size)#>
【Static method: Buffer.allocUnsafeSlow(size)】
分配一个大小为 size 字节的新 Buffer。如果 size 大于 buffer.constants.MAX_LENGTH 或小于 0,则会抛出 ERR_OUT_OF_RANGE。如果 size 为 0,则会创建一个长度为零的 Buffer。
【Allocates a new Buffer of size bytes. If size is larger than
buffer.constants.MAX_LENGTH or smaller than 0, ERR_OUT_OF_RANGE
is thrown. A zero-length Buffer is created if size is 0.】
以这种方式创建的 Buffer 实例的底层内存未初始化。新创建的 Buffer 的内容未知,可能包含敏感数据。使用 buf.fill(0) 将这些 Buffer 实例初始化为零。
【The underlying memory for Buffer instances created in this way is not
initialized. The contents of the newly created Buffer are unknown and
may contain sensitive data. Use buf.fill(0) to initialize
such Buffer instances with zeroes.】
在使用 Buffer.allocUnsafe() 分配新的 Buffer 实例时,小于 Buffer.poolSize >>> 1(当使用默认 poolSize 时为 4KiB)的分配将从单个预分配的 Buffer 中切片。这使得应用可以避免创建许多单独分配的 Buffer 实例所带来的垃圾回收开销。这种方法通过无需跟踪和清理这么多单独的 ArrayBuffer 对象,从而提高了性能和内存使用效率。
【When using Buffer.allocUnsafe() to allocate new Buffer instances,
allocations less than Buffer.poolSize >>> 1 (4KiB when default poolSize is used) are sliced
from a single pre-allocated Buffer. This allows applications to avoid the
garbage collection overhead of creating many individually allocated Buffer
instances. This approach improves both performance and memory usage by
eliminating the need to track and clean up as many individual ArrayBuffer objects.】
然而,在开发者可能需要从内存池中保留一小块内存且时间不确定的情况下,使用 Buffer.allocUnsafeSlow() 创建一个非池化的 Buffer 实例,然后复制出相关部分,可能是合适的做法。
【However, in the case where a developer may need to retain a small chunk of
memory from a pool for an indeterminate amount of time, it may be appropriate
to create an un-pooled Buffer instance using Buffer.allocUnsafeSlow() and
then copying out the relevant bits.】
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。
【A TypeError will be thrown if size is not a number.】
静态方法:Buffer.byteLength(string[, encoding])#>
【Static method: Buffer.byteLength(string[, encoding])】
string<string> | <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <SharedArrayBuffer> 要计算长度的值。encoding<string> 如果string是字符串,则这是它的编码。 默认值:'utf8'。- 返回值: <integer>
string中包含的字节数。
返回使用 encoding 编码时字符串的字节长度。这与 String.prototype.length 不同,后者未考虑用于将字符串转换为字节的编码方式。
【Returns the byte length of a string when encoded using encoding.
This is not the same as String.prototype.length, which does not account
for the encoding that is used to convert the string into bytes.】
对于 'base64'、'base64url' 和 'hex',此函数假设输入有效。对于包含非 base64/hex 编码数据(例如空格)的字符串,返回值可能大于从该字符串创建的 Buffer 的长度。
【For 'base64', 'base64url', and 'hex', this function assumes valid input.
For strings that contain non-base64/hex-encoded data (e.g. whitespace), the
return value might be greater than the length of a Buffer created from the
string.】
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 返回的就是字节长度。
【When string is a <Buffer> | <DataView> | <TypedArray> | <ArrayBuffer> | <SharedArrayBuffer>,
the byte length as reported by .byteLength is returned.】
静态方法:Buffer.compare(buf1, buf2)#>
【Static method: Buffer.compare(buf1, buf2)】
buf1<Buffer> | <Uint8Array>buf2<Buffer> | <Uint8Array>- 返回值: <integer> 根据比较结果,返回
-1、0或1。详情请参阅buf.compare()。
buf1 与 buf2 进行比较,通常用于对 Buffer 实例数组进行排序。这相当于调用 buf1.compare(buf2)。
【Compares buf1 to buf2, typically for the purpose of sorting arrays of
Buffer instances. This is equivalent to calling
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])#>
【Static method: Buffer.concat(list[, totalLength])】
- '列表' <Uint8Array[]> “缓冲区”或 <Uint8Array> 列表 实例需要串接。
- 'totalLength' <integer> 'list' 中'缓冲区'实例的总长度 当连接时。
- 回归时间:<Buffer>
返回一个新的 Buffer,它是将 list 中的所有 Buffer 实例连接在一起的结果。
【Returns a new Buffer which is the result of concatenating all the Buffer
instances in the list together.】
如果列表没有项目,或者 totalLength 为 0,则会返回一个新的零长度 Buffer。
【If the list has no items, or if the totalLength is 0, then a new zero-length
Buffer is returned.】
如果未提供 totalLength,则通过将 list 中 Buffer 实例的长度相加来计算。
【If totalLength is not provided, it is calculated from the Buffer instances
in list by adding their lengths.】
如果提供了 totalLength,它会被强制转换为无符号整数。如果 list 中 Buffer 的总长度超过 totalLength,结果将被截断为 totalLength。如果 list 中 Buffer 的总长度小于 totalLength,剩余空间将用零填充。
【If totalLength is provided, it is coerced to an unsigned integer. If the
combined length of the Buffers in list exceeds totalLength, the result is
truncated to totalLength. If the combined length of the Buffers in list is
less than totalLength, the remaining space is filled with zeros.】
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]])#>
【Static method: Buffer.copyBytesFrom(view[, offset[, length]])】
view<TypedArray> 要复制的 <TypedArray>。offset<integer>view中的起始偏移量。默认值:0。length<integer> 从view中要复制的元素数量。默认值:view.length - offset。- 返回值:<Buffer>
将 view 的底层内存复制到新的 Buffer 中。
【Copies the underlying memory of view into a new 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)#>
【Static method: Buffer.from(array)】
- '数组' 整数[]
- 回归:<Buffer>
使用范围为 0–255 的字节数组分配一个新的 Buffer。数组中超出该范围的条目将被截断以适应该范围。
【Allocates a new Buffer using an array of bytes in the range 0 – 255.
Array entries outside that range will be truncated to fit into it.】
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 是一个类似 Array 的对象(即具有 number 类型的 length 属性),它会被当作数组处理,除非它是 Buffer 或 Uint8Array。这意味着所有其他 TypedArray 变体都被当作 Array 处理。要从支持 TypedArray 的字节创建 Buffer,请使用 Buffer.copyBytesFrom()。
【If array is an Array-like object (that is, one with a length property of
type number), it is treated as if it is an array, unless it is a Buffer or
a Uint8Array. This means all other TypedArray variants get treated as an
Array. To create a Buffer from the bytes backing a TypedArray, use
Buffer.copyBytesFrom().】
如果 array 不是 Array 或其他适用于 Buffer.from() 的类型,将会抛出 TypeError。
【A TypeError will be thrown if array is not an Array or another type
appropriate for Buffer.from() variants.】
Buffer.from(array) 和 Buffer.from(string) 也可能像 Buffer.allocUnsafe() 一样使用内部 Buffer 池。
静态方法:Buffer.from(arrayBuffer[, byteOffset[, length]])#>
【Static method: Buffer.from(arrayBuffer[, byteOffset[, length]])】
arrayBuffer<ArrayBuffer> | <SharedArrayBuffer> 一个 <ArrayBuffer>,例如 <TypedArray> 的.buffer属性。byteOffset<integer> 要暴露的第一个字节的索引。默认值:0。length<integer> 要暴露的字节数。默认值:arrayBuffer.byteLength - byteOffset。- 返回值:<Buffer>
这会创建一个 <ArrayBuffer> 的视图,而不会复制底层内存。例如,当传入 <TypedArray> 实例的 .buffer 属性的引用时,新创建的 Buffer 将与 <TypedArray> 的底层 ArrayBuffer 共享相同的已分配内存。
【This creates a view of the <ArrayBuffer> without copying the underlying
memory. For example, when passed a reference to the .buffer property of a
<TypedArray> instance, the newly created Buffer will share the same
allocated memory as the <TypedArray>'s underlying 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 参数指定 Buffer 将共享的 arrayBuffer 内的内存范围。
【The optional byteOffset and length arguments specify a memory range within
the arrayBuffer that will be shared by the 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。
【A TypeError will be thrown if arrayBuffer is not an <ArrayBuffer> or a
<SharedArrayBuffer> or another type appropriate for Buffer.from()
variants.】
重要的是要记住,作为后盾的 ArrayBuffer 可以覆盖超出 TypedArray 视图边界的内存范围。使用 TypedArray 的 buffer 属性创建的新 Buffer 可能会超出 TypedArray 的范围:
【It is important to remember that a backing ArrayBuffer can cover a range
of memory that extends beyond the bounds of a TypedArray view. A new
Buffer created using the buffer property of a TypedArray may extend
beyond the range of the 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)#>
【Static method: Buffer.from(buffer)】
buffer<Buffer> | <Uint8Array> 一个已有的Buffer或 <Uint8Array>,用于复制数据。- 返回值:<Buffer>
将传入的 buffer 数据复制到一个新的 Buffer 实例中。
【Copies the passed buffer data onto a new Buffer instance.】
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。
【A TypeError will be thrown if buffer is not a Buffer or another type
appropriate for Buffer.from() variants.】
静态方法:Buffer.from(object[, offsetOrEncoding[, length]])#>
【Static method: Buffer.from(object[, offsetOrEncoding[, length]])】
object<Object> 支持Symbol.toPrimitive或valueOf()的对象。offsetOrEncoding<integer> | <string> 字节偏移量或编码。length<integer> 长度。- 返回: <Buffer>
对于其 valueOf() 函数返回的值不严格等于 object 的对象,返回 Buffer.from(object.valueOf(), offsetOrEncoding, length)。
【For objects whose valueOf() function returns a value not strictly equal to
object, returns 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)。
【For objects that support Symbol.toPrimitive, returns
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。
【A TypeError will be thrown if object does not have the mentioned methods or
is not of another type appropriate for Buffer.from() variants.】
静态方法:Buffer.from(string[, encoding])#>
【Static method: Buffer.from(string[, encoding])】
创建一个包含 string 的新 Buffer。encoding 参数用于指定将 string 转换为字节时使用的字符编码。
【Creates a new Buffer containing string. The encoding parameter identifies
the character encoding to be used when converting string into bytes.】
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。
【A TypeError will be thrown if string is not a string or another type
appropriate for Buffer.from() variants.】
Buffer.from(string) 也可能像 Buffer.allocUnsafe() 那样使用内部 Buffer 池。
静态方法:Buffer.isBuffer(obj)#>
【Static method: Buffer.isBuffer(obj)】
如果 obj 是一个 Buffer,则返回 true,否则返回 false。
【Returns true if obj is a Buffer, false otherwise.】
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)#>
【Static method: Buffer.isEncoding(encoding)】
如果 encoding 是支持的字符编码名称,则返回 true,否则返回 false。
【Returns true if encoding is the name of a supported character encoding,
or false otherwise.】
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
Buffer.poolSize#>
- 类型: <integer> 默认值:
8192
这是用于池化的预分配内部 Buffer 实例的大小(以字节为单位)。此值可以修改。
【This is the size (in bytes) of pre-allocated internal Buffer instances used
for pooling. This value may be modified.】
buf[index]#>
index<integer>
索引操作符 [index] 可用于获取和设置 buf 中索引位置 index 的字节。数值指的是单个字节,因此合法的取值范围是 0x00 到 0xFF(十六进制)或 0 到 255(十进制)。
【The index operator [index] can be used to get and set the octet at position
index in buf. The values refer to individual bytes, so the legal value
range is between 0x00 and 0xFF (hex) or 0 and 255 (decimal).】
这个操作符继承自 Uint8Array,因此它在越界访问时的行为与 Uint8Array 相同。换句话说,当 index 为负或大于等于 buf.length 时,buf[index] 返回 undefined,而 buf[index] = value 在 index 为负或 >= buf.length 时不会修改缓冲区。
【This operator is inherited from Uint8Array, so its behavior on out-of-bounds
access is the same as Uint8Array. In other words, buf[index] returns
undefined when index is negative or greater or equal to buf.length, and
buf[index] = value does not modify the buffer if index is negative or
>= buf.length.】
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 的说明。
【This ArrayBuffer is not guaranteed to correspond exactly to the original
Buffer. See the notes on buf.byteOffset for details.】
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 的零偏移量开始的。
【When setting byteOffset in Buffer.from(ArrayBuffer, byteOffset, length),
or sometimes when allocating a Buffer smaller than Buffer.poolSize, the
buffer does not start from a zero offset on the underlying ArrayBuffer.】
在使用 buf.buffer 直接访问底层 ArrayBuffer 时,这可能会引发问题,因为 ArrayBuffer 的其他部分可能与 Buffer 对象本身无关。
【This can cause problems when accessing the underlying ArrayBuffer directly
using buf.buffer, as other parts of the ArrayBuffer may be unrelated
to the Buffer object itself.】
在创建与 Buffer 共享内存的 TypedArray 对象时,一个常见的问题是需要正确指定 byteOffset:
【A common issue when creating a TypedArray object that shares its memory with
a Buffer is that in this case one needs to specify the byteOffset correctly:】
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 之前、之后还是与 target 相同。比较是基于每个 Buffer 中的实际字节序列。
【Compares buf with target and returns a number indicating whether buf
comes before, after, or is the same as target in sort order.
Comparison is based on the actual sequence of bytes in each 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 中的特定范围内。
【The optional targetStart, targetEnd, sourceStart, and sourceEnd
arguments can be used to limit the comparison to specific ranges within target
and buf respectively.】
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 重叠也可以。
【Copies data from a region of buf to a region in target, even if the target
memory region overlaps with 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] 对的 迭代器。
【Creates and returns an iterator of [index, byte] pairs from the contents
of buf.】
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。
【Returns true if both buf and otherBuffer have exactly the same bytes,
false otherwise. Equivalent to
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 都会被填充:
【Fills buf with the specified value. If the offset and end are not given,
the entire buf will be filled:】
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 会被强制转为 uint32 值,如果它不是字符串、Buffer 或整数。如果得到的整数大于 255(十进制),buf 将会被填充为 value & 255。
如果 fill() 操作的最终写入发生在一个多字节字符上,那么只有能够放入 buf 的该字符的字节会被写入:
【If the final write of a fill() operation falls on a multi-byte character,
then only the bytes of that character that fit into buf are written:】
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 包含无效字符,则会被截断;如果没有剩余有效的填充数据,则会抛出异常:
【If value contains invalid characters, it is truncated; if no valid
fill data remains, an exception is thrown:】
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。
【Equivalent to 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>
value在buf中首次出现的位置的索引,如果buf不包含value,则返回-1。
如果 value 是:
【If value is:】
- 字符串,
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 之间的整数。
【If value is not a string, number, or Buffer, this method will throw a
TypeError. If value is a number, it will be coerced to a valid byte value,
an integer between 0 and 255.】
如果 byteOffset 不是一个数字,它将被强制转换为数字。如果强制转换的结果是 NaN 或 0,那么整个缓冲区将被搜索。此行为与 String.prototype.indexOf() 一致。
【If byteOffset is not a number, it will be coerced to a number. If the result
of coercion is NaN or 0, then the entire buffer will be searched. This
behavior matches 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。
【If value is an empty string or empty Buffer and byteOffset is less
than buf.length, byteOffset will be returned. If value is empty and
byteOffset is at least buf.length, buf.length will be returned.】
buf.keys()#>
- 返回: <Iterator>
创建并返回 buf 键(索引)的 迭代器。
【Creates and returns an iterator of buf keys (indexes).】
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>
value在buf中最后一次出现的索引,如果buf不包含value,则返回-1。
与 buf.indexOf() 相同,不同之处在于找到的是 value 的最后一次出现,而不是第一次出现。
【Identical to buf.indexOf(), except the last occurrence of value is found
rather than the first occurrence.】
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 之间的整数。
【If value is not a string, number, or Buffer, this method will throw a
TypeError. If value is a number, it will be coerced to a valid byte value,
an integer between 0 and 255.】
如果 byteOffset 不是数字,它将被强制转换为数字。任何会被强制转换为 NaN 的参数,如 {} 或 undefined,将搜索整个缓冲区。此行为与 String.prototype.lastIndexOf() 相匹配。
【If byteOffset is not a number, it will be coerced to a number. Any arguments
that coerce to NaN, like {} or undefined, will search the whole buffer.
This behavior matches 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。
【If value is an empty string or empty Buffer, byteOffset will be returned.】
buf.length#>
- 类型: <integer>
返回 buf 中的字节数。
【Returns the number of bytes in 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.parent#>
buf.buffer。buf.parent 属性是 buf.buffer 的已弃用别名。
【The buf.parent property is a deprecated alias for buf.buffer.】
buf.readBigInt64BE([offset])#>
从指定的 offset 处的 buf 中读取一个带符号的大端 64 位整数。
【Reads a signed, big-endian 64-bit integer from buf at the specified offset.】
从 Buffer 读取的整数被解释为二进制补码的有符号值。
【Integers read from a Buffer are interpreted as two's complement signed
values.】
buf.readBigInt64LE([offset])#>
从 buf 在指定的 offset 处读取一个带符号、小端字节序的 64 位整数。
【Reads a signed, little-endian 64-bit integer from buf at the specified
offset.】
从 Buffer 读取的整数被解释为二进制补码的有符号值。
【Integers read from a Buffer are interpreted as two's complement signed
values.】
buf.readBigUInt64BE([offset])#>
从 buf 在指定的 offset 处读取一个无符号的大端 64 位整数。
【Reads an unsigned, big-endian 64-bit integer from buf at the specified
offset.】
这个函数也可以通过 readBigUint64BE 别名使用。
【This function is also available under the readBigUint64BE alias.】
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 位整数。
【Reads an unsigned, little-endian 64-bit integer from buf at the specified
offset.】
这个函数也可以通过 readBigUint64LE 别名使用。
【This function is also available under the readBigUint64LE alias.】
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])#>
从指定的 offset 在 buf 中读取一个 64 位大端双精度浮点数。
【Reads a 64-bit, big-endian double from buf at the specified offset.】
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])#>
从指定的 offset 在 buf 中读取一个 64 位小端双精度浮点数。
【Reads a 64-bit, little-endian double from buf at the specified offset.】
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])#>
从指定的 offset 在 buf 中读取一个 32 位大端浮点数。
【Reads a 32-bit, big-endian float from buf at the specified offset.】
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])#>
从指定的 offset 在 buf 中读取一个 32 位小端浮点数。
【Reads a 32-bit, little-endian float from buf at the specified offset.】
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 位整数。
【Reads a signed 8-bit integer from buf at the specified offset.】
从 Buffer 读取的整数被解释为二进制补码的有符号值。
【Integers read from a Buffer are interpreted as two's complement signed values.】
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])#>
从指定的 offset 处的 buf 中读取一个带符号的大端 16 位整数。
【Reads a signed, big-endian 16-bit integer from buf at the specified offset.】
从 Buffer 读取的整数被解释为二进制补码的有符号值。
【Integers read from a Buffer are interpreted as two's complement signed values.】
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])#>
从指定的 offset 处的 buf 中读取一个带符号的小端 16 位整数。
【Reads a signed, little-endian 16-bit integer from buf at the specified
offset.】
从 Buffer 读取的整数被解释为二进制补码的有符号值。
【Integers read from a Buffer are interpreted as two's complement signed values.】
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])#>
从指定的 offset 处的 buf 中读取一个带符号的大端32位整数。
【Reads a signed, big-endian 32-bit integer from buf at the specified offset.】
从 Buffer 读取的整数被解释为二进制补码的有符号值。
【Integers read from a Buffer are interpreted as two's complement signed values.】
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 位整数。
【Reads a signed, little-endian 32-bit integer from buf at the specified
offset.】
从 Buffer 读取的整数被解释为二进制补码的有符号值。
【Integers read from a Buffer are interpreted as two's complement signed values.】
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 位的精度。
【Reads byteLength number of bytes from buf at the specified offset
and interprets the result as a big-endian, two's complement signed value
supporting up to 48 bits of accuracy.】
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 位的精度。
【Reads byteLength number of bytes from buf at the specified offset
and interprets the result as a little-endian, two's complement signed value
supporting up to 48 bits of accuracy.】
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 位整数。
【Reads an unsigned 8-bit integer from buf at the specified offset.】
该函数也可以通过 readUint8 别名使用。
【This function is also available under the readUint8 alias.】
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])#>
从指定的 offset 处的 buf 中读取一个无符号大端 16 位整数。
【Reads an unsigned, big-endian 16-bit integer from buf at the specified
offset.】
这个函数也可以通过 readUint16BE 别名使用。
【This function is also available under the readUint16BE alias.】
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])#>
从指定的 offset 处的 buf 中读取一个无符号的小端 16 位整数。
【Reads an unsigned, little-endian 16-bit integer from buf at the specified
offset.】
这个函数也可以通过 readUint16LE 别名使用。
【This function is also available under the readUint16LE alias.】
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位整数。
【Reads an unsigned, big-endian 32-bit integer from buf at the specified
offset.】
这个函数也可以通过 readUint32BE 别名使用。
【This function is also available under the readUint32BE alias.】
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])#>
从指定的 offset 处的 buf 中读取一个无符号的小端 32 位整数。
【Reads an unsigned, little-endian 32-bit integer from buf at the specified
offset.】
这个函数也可以通过 readUint32LE 别名使用。
【This function is also available under the readUint32LE alias.】
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>
从指定的 offset 位置的 buf 中读取 byteLength 个字节,并将结果解释为无符号大端整数,最多支持 48 位精度。
【Reads byteLength number of bytes from buf at the specified offset
and interprets the result as an unsigned big-endian integer supporting
up to 48 bits of accuracy.】
该函数也可以通过 readUintBE 别名使用。
【This function is also available under the readUintBE alias.】
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 位的精度。
【Reads byteLength number of bytes from buf at the specified offset
and interprets the result as an unsigned, little-endian integer supporting
up to 48 bits of accuracy.】
该函数也可以通过 readUintLE 别名使用。
【This function is also available under the readUintLE alias.】
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 索引进行了偏移和裁剪。
【Returns a new Buffer that references the same memory as the original, but
offset and cropped by the start and end indexes.】
指定 end 大于 buf.length 将返回与 end 等于 buf.length 相同的结果。
【Specifying end greater than buf.length will return the same result as
that of end equal to buf.length.】
此方法继承自 TypedArray.prototype.subarray()。
【This method is inherited from TypedArray.prototype.subarray().】
修改新的 Buffer 切片会修改原始 Buffer 中的内存,因为两个对象分配的内存是重叠的。
【Modifying the new Buffer slice will modify the memory in the original Buffer
because the allocated memory of the two objects overlap.】
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 的末尾而不是开头生成。
【Specifying negative indexes causes the slice to be generated relative to the
end of buf rather than the beginning.】
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 索引进行了偏移和裁剪。
【Returns a new Buffer that references the same memory as the original, but
offset and cropped by the start and end indexes.】
此方法与 Uint8Array.prototype.slice() 不兼容,Uint8Array.prototype.slice() 是 Buffer 的超类。若要复制切片,请使用 Uint8Array.prototype.slice()。
【This method is not compatible with the Uint8Array.prototype.slice(),
which is a superclass of Buffer. To copy the slice, use
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。
【Interprets buf as an array of unsigned 16-bit integers and swaps the
byte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length
is not a multiple of 2.】
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 大端之间的快速原地转换:
【One convenient use of buf.swap16() is to perform a fast in-place conversion
between UTF-16 little-endian and UTF-16 big-endian:】
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。
【Interprets buf as an array of unsigned 32-bit integers and swaps the
byte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length
is not a multiple of 4.】
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。
【Interprets buf as an array of 64-bit numbers and swaps byte order in-place.
Throws ERR_INVALID_BUFFER_SIZE if buf.length is not a multiple of 8.】
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 表示。JSON.stringify() 在将 Buffer 实例转换为字符串时会隐式调用此函数。
【Returns a JSON representation of buf. JSON.stringify() implicitly calls
this function when stringifying a Buffer instance.】
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 的一部分。
【Decodes buf to a string according to the specified character encoding in
encoding. start and end may be passed to decode only a subset of buf.】
如果 encoding 为 'utf8',且输入中的字节序列不是有效的 UTF-8,则每个无效字节都会被替换为替代字符 U+FFFD。
【If encoding is 'utf8' and a byte sequence in the input is not valid UTF-8,
then each invalid byte is replaced with the replacement character U+FFFD.】
字符串实例的最大长度(以 UTF-16 代码单元计)可通过 buffer.constants.MAX_STRING_LENGTH 获得。
【The maximum length of a string instance (in UTF-16 code units) is available
as 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 值(字节)创建并返回一个 迭代器。当 Buffer 在 for..of 语句中使用时,本函数会被自动调用。
【Creates and returns an iterator for buf values (bytes). This function is
called automatically when a Buffer is used in a for..of statement.】
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 中的字符编码,将 string 写入 buf 的 offset 位置。参数 length 是要写入的字节数。如果 buf 没有足够的空间容纳整个字符串,则只会写入部分 string。但是,部分编码的字符将不会被写入。
【Writes string to buf at offset according to the character encoding in
encoding. The length parameter is the number of bytes to write. If buf did
not contain enough space to fit the entire string, only part of string will be
written. However, partially encoded characters will not be written.】
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,采用大端格式。
【Writes value to buf at the specified offset as big-endian.】
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 以小端格式写入指定 offset 的 buf。
【Writes value to buf at the specified offset as little-endian.】
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,采用大端格式。
【Writes value to buf at the specified offset as big-endian.】
这个函数也可以通过 writeBigUint64BE 别名使用。
【This function is also available under the writeBigUint64BE alias.】
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
【Writes value to buf at the specified offset as little-endian】
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 别名使用。
【This function is also available under the writeBigUint64LE alias.】
buf.writeDoubleBE(value[, offset])#>
value<number> 要写入buf的数字。offset<integer> 写入前要跳过的字节数。必须满足0 <= offset <= buf.length - 8。默认值:0。- 返回值:<integer>
offset加上写入的字节数。
将 value 以大端格式写入指定 offset 的 buf。value 必须是 JavaScript 数字。当 value 不是 JavaScript 数字时,行为是未定义的。
【Writes value to buf at the specified offset as big-endian. The value
must be a JavaScript number. Behavior is undefined when value is anything
other than a JavaScript number.】
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 以小端格式写入指定 offset 的 buf。value 必须是 JavaScript 数字。当 value 不是 JavaScript 数字时,行为是未定义的。
【Writes value to buf at the specified offset as little-endian. The value
must be a JavaScript number. Behavior is undefined when value is anything
other than a JavaScript number.】
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 数字时,行为未定义。
【Writes value to buf at the specified offset as big-endian. Behavior is
undefined when value is anything other than a JavaScript number.】
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 数字时,行为未定义。
【Writes value to buf at the specified offset as little-endian. Behavior is
undefined when value is anything other than a JavaScript number.】
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 位整数时,其行为未定义。
【Writes value to buf at the specified offset. value must be a valid
signed 8-bit integer. Behavior is undefined when value is anything other than
a signed 8-bit integer.】
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 以大端格式写入指定 offset 的 buf。value 必须是有效的有符号 16 位整数。当 value 不是有符号 16 位整数时,行为未定义。
【Writes value to buf at the specified offset as big-endian. The value
must be a valid signed 16-bit integer. Behavior is undefined when value is
anything other than a signed 16-bit integer.】
value 被解释并写入为二进制补码有符号整数。
【The value is interpreted and written as a two's complement signed integer.】
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 以小端格式写入指定 offset 的 buf。value 必须是有效的有符号 16 位整数。当 value 不是有符号 16 位整数时,行为是未定义的。
【Writes value to buf at the specified offset as little-endian. The value
must be a valid signed 16-bit integer. Behavior is undefined when value is
anything other than a signed 16-bit integer.】
value 被解释并写入为二进制补码有符号整数。
【The value is interpreted and written as a two's complement signed integer.】
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 以大端模式写入指定 offset 的 buf。value 必须是有效的有符号 32 位整数。当 value 不是有符号 32 位整数时,行为未定义。
【Writes value to buf at the specified offset as big-endian. The value
must be a valid signed 32-bit integer. Behavior is undefined when value is
anything other than a signed 32-bit integer.】
value 被解释并写入为二进制补码有符号整数。
【The value is interpreted and written as a two's complement signed integer.】
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 以小端格式写入指定 offset 的 buf。value 必须是有效的有符号 32 位整数。当 value 不是有符号 32 位整数时,行为未定义。
【Writes value to buf at the specified offset as little-endian. The value
must be a valid signed 32-bit integer. Behavior is undefined when value is
anything other than a signed 32-bit integer.】
value 被解释并写入为二进制补码有符号整数。
【The value is interpreted and written as a two's complement signed integer.】
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 字节以大端序写入指定 offset 的 buf。支持最多 48 位精度。当 value 不是有符号整数时,行为未定义。
【Writes byteLength bytes of value to buf at the specified offset
as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when
value is anything other than a signed integer.】
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 字节以小端格式写入指定 offset 的 buf。支持最多 48 位精度。当 value 不是有符号整数时,行为未定义。
【Writes byteLength bytes of value to buf at the specified offset
as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
when value is anything other than a signed integer.】
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 位整数时,行为是未定义的。
【Writes value to buf at the specified offset. value must be a
valid unsigned 8-bit integer. Behavior is undefined when value is anything
other than an unsigned 8-bit integer.】
该函数也可以通过 writeUint8 别名使用。
【This function is also available under the writeUint8 alias.】
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 以大端格式写入指定 offset 处的 buf。value 必须是有效的无符号 16 位整数。当 value 不是无符号 16 位整数时,行为是未定义的。
【Writes value to buf at the specified offset as big-endian. The value
must be a valid unsigned 16-bit integer. Behavior is undefined when value
is anything other than an unsigned 16-bit integer.】
这个函数也可以通过 writeUint16BE 别名使用。
【This function is also available under the writeUint16BE alias.】
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 以小端格式写入指定 offset 的 buf。value 必须是有效的无符号 16 位整数。当 value 不是无符号 16 位整数时,行为未定义。
【Writes value to buf at the specified offset as little-endian. The value
must be a valid unsigned 16-bit integer. Behavior is undefined when value is
anything other than an unsigned 16-bit integer.】
这个函数也可以通过 writeUint16LE 别名使用。
【This function is also available under the writeUint16LE alias.】
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 以大端格式写入指定 offset 处的 buf。value 必须是有效的无符号 32 位整数。当 value 不是无符号 32 位整数时,行为是未定义的。
【Writes value to buf at the specified offset as big-endian. The value
must be a valid unsigned 32-bit integer. Behavior is undefined when value
is anything other than an unsigned 32-bit integer.】
这个函数也可以通过 writeUint32BE 别名使用。
【This function is also available under the writeUint32BE alias.】
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 以小端格式写入指定 offset 的 buf。value 必须是有效的无符号 32 位整数。当 value 不是无符号 32 位整数时,行为未定义。
【Writes value to buf at the specified offset as little-endian. The value
must be a valid unsigned 32-bit integer. Behavior is undefined when value is
anything other than an unsigned 32-bit integer.】
这个函数也可以通过 writeUint32LE 别名使用。
【This function is also available under the writeUint32LE alias.】
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 字节以大端序写入指定 offset 的 buf。支持最多 48 位精度。当 value 不是无符号整数时,行为未定义。
【Writes byteLength bytes of value to buf at the specified offset
as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined
when value is anything other than an unsigned integer.】
该函数也可以通过 writeUintBE 别名使用。
【This function is also available under the writeUintBE alias.】
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 字节以小端格式写入指定 offset 的 buf。支持最多 48 位精度。当 value 不是无符号整数时,行为未定义。
【Writes byteLength bytes of value to buf at the specified offset
as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
when value is anything other than an unsigned integer.】
该函数也可以通过 writeUintLE 别名使用。
【This function is also available under the writeUintLE alias.】
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(array)#>
Buffer.from(array)。array整数数组[] 要复制的字节数组。
【See Buffer.from(array).】
new Buffer(arrayBuffer[, byteOffset[, length]])#>
Buffer.from(arrayBuffer[, byteOffset[, length]]) 代替。arrayBuffer<ArrayBuffer> | <SharedArrayBuffer> 一个 <ArrayBuffer>,<SharedArrayBuffer> 或者 <TypedArray> 的.buffer属性。byteOffset<integer> 要暴露的第一个字节的索引。默认值:0。length<integer> 要暴露的字节数。默认值:arrayBuffer.byteLength - byteOffset。
请参阅 Buffer.from(arrayBuffer[, byteOffset[, length]])。
【See
Buffer.from(arrayBuffer[, byteOffset[, length]]).】
new Buffer(buffer)#>
Buffer.from(buffer)。buffer<Buffer> | <Uint8Array> 一个现有的Buffer或 <Uint8Array>,用于复制数据。
【See Buffer.from(buffer).】
new Buffer(size)#>
size<integer> 新Buffer的期望长度。
参见 Buffer.alloc() 和 Buffer.allocUnsafe()。这种构造函数的变体等同于 Buffer.alloc()。
【See Buffer.alloc() and Buffer.allocUnsafe(). This variant of the
constructor is equivalent to Buffer.alloc().】
new Buffer(string[, encoding])#>
Buffer.from(string[, encoding])。请参阅 Buffer.from(string[, encoding])。
类:File#>
【Class: File】
- 继承: <Blob>
一个 <File> 提供有关文件的信息。
【A <File> provides information about files.】
new buffer.File(sources, fileName[, options])#>
- “资料来源” <string[]> | <ArrayBuffer[]> | <TypedArray[]> | <DataView[]> 字符串数组为<ArrayBuffer>、<TypedArray>、<DataView>、<File>或<Blob> 这些对象,或其任意组合,将存储在“文件”中。
- “文件名” <string> 文件名称。
- “选项” <Object>
file.name#>
- 类型: <string>
File 的名称。
【The name of the File.】
file.lastModified#>
- 类型: <number>
File 的最后修改日期。
【The last modified date of the File.】
node:buffer 模块 API#>
【node:buffer module APIs】
虽然 Buffer 对象作为全局对象可用,但还有一些与 Buffer 相关的 API,仅可通过使用 require('node:buffer') 访问的 node:buffer 模块获得。
【While, the Buffer object is available as a global, there are additional
Buffer-related APIs that are available only via the node:buffer module
accessed using require('node:buffer').】
buffer.atob(data)#>
Buffer.from(data, 'base64')。data<any> 基于 Base64 编码的输入字符串。
将一串 Base64 编码的数据解码为字节,然后使用 Latin-1(ISO-8859-1)将这些字节编码为字符串。
【Decodes a string of Base64-encoded data into bytes, and encodes those bytes into a string using Latin-1 (ISO-8859-1).】
data 可以是任何可以被强制转换为字符串的 JavaScript 值。
【The data may be any JavaScript-value that can be coerced into a string.】
此函数仅为兼容旧版 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 将这些字节编码为字符串。
【Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes into a string using Base64.】
data 可以是任何可以被强制转换为字符串的 JavaScript 值。
【The data may be any JavaScript-value that can be coerced into a string.】
此函数仅为兼容旧版 Web 平台 API 而提供,不应在新代码中使用,因为它们使用字符串来表示二进制数据,并且早于 JavaScript 中引入的类型化数组。
对于使用 Node.js API 运行的代码,应使用 Buffer.from(str, 'base64') 和 buf.toString('base64') 在 Base64 编码字符串与二进制数据之间进行转换。
buffer.isAscii(input)#>
input<Buffer> | <ArrayBuffer> | <TypedArray> 要验证的输入。- 返回: <boolean>
如果 input 仅包含有效的 ASCII 编码数据,包括 input 为空的情况,则此函数返回 true。
【This function returns true if input contains only valid ASCII-encoded data,
including the case in which input is empty.】
如果 input 是已分离的数组缓冲区,则会抛出异常。
【Throws if the input is a detached array buffer.】
buffer.isUtf8(input)#>
input<Buffer> | <ArrayBuffer> | <TypedArray> 要验证的输入。- 返回: <boolean>
如果 input 只包含有效的 UTF-8 编码数据(包括 input 为空的情况),此函数将返回 true。
【This function returns true if input contains only valid UTF-8-encoded data,
including the case in which input is empty.】
如果 input 是已分离的数组缓冲区,则会抛出异常。
【Throws if the input is a detached array buffer.】
buffer.INSPECT_MAX_BYTES#>
- 类型: <integer> 默认值:
50
返回调用 buf.inspect() 时将返回的最大字节数。用户模块可以覆盖此值。有关 buf.inspect() 行为的更多详细信息,请参见 util.inspect()。
【Returns the maximum number of bytes that will be returned when
buf.inspect() is called. This can be overridden by user modules. See
util.inspect() for more details on buf.inspect() behavior.】
buffer.kMaxLength#>
- 类型: <integer> 单个
Buffer实例允许的最大大小。
buffer.constants.MAX_LENGTH 的别名。
【An alias for buffer.constants.MAX_LENGTH.】
buffer.kStringMaxLength#>
- 类型: <integer> 单个
string实例允许的最大长度。
buffer.constants.MAX_STRING_LENGTH 的别名。
【An alias for buffer.constants.MAX_STRING_LENGTH.】
buffer.resolveObjectURL(id)#>
解析通过先前调用 URL.createObjectURL() 注册的 'blob:nodedata:...' 相关的 <Blob> 对象。
【Resolves a 'blob:nodedata:...' an associated <Blob> object registered using
a prior call to URL.createObjectURL().】
buffer.transcode(source, fromEnc, toEnc)#>
source<Buffer> | <Uint8Array> 一个Buffer或Uint8Array实例。fromEnc<string> 当前的编码。toEnc<string> 目标编码。- 返回: <Buffer>
将给定的 Buffer 或 Uint8Array 实例从一种字符编码重新编码为另一种字符编码。返回一个新的 Buffer 实例。
【Re-encodes the given Buffer or Uint8Array instance from one character
encoding to another. Returns a new Buffer instance.】
如果 fromEnc 或 toEnc 指定了无效的字符编码,或者从 fromEnc 转换到 toEnc 不被允许,将抛出异常。
【Throws if the fromEnc or toEnc specify invalid character encodings or if
conversion from fromEnc to toEnc is not permitted.】
buffer.transcode() 支持的编码有:'ascii'、'utf8'、'utf16le'、'ucs2'、'latin1' 和 'binary'。
【Encodings supported by buffer.transcode() are: 'ascii', 'utf8',
'utf16le', 'ucs2', 'latin1', and 'binary'.】
如果给定的字节序列无法在目标编码中被充分表示,转码过程将使用替代字符。例如:
【The transcoding process will use substitution characters if a given byte sequence cannot be adequately represented in the target encoding. For instance:】
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 中会被替换为 ?。
【Because the Euro (€) sign is not representable in US-ASCII, it is replaced
with ? in the transcoded Buffer.】
类:SlowBuffer#>
【Class: SlowBuffer】
Buffer.allocUnsafeSlow()。参见 Buffer.allocUnsafeSlow()。这从来不是一个类,因为构造函数总是返回一个 Buffer 实例,而不是 SlowBuffer 实例。
【See Buffer.allocUnsafeSlow(). This was never a class in the sense that
the constructor always returned a Buffer instance, rather than a SlowBuffer
instance.】
new SlowBuffer(size)#>
size<integer> 新SlowBuffer所需的长度。
【See Buffer.allocUnsafeSlow().】
缓冲区常量#>
【Buffer constants】
buffer.constants.MAX_LENGTH#>
- 类型: <integer> 单个
Buffer实例允许的最大大小。
在32位架构上,该值目前是 230 -1(约 1 GiB)。
在64位架构上,该值目前是253 -1(约8 PiB)。
它在内部反映了 v8::TypedArray::kMaxLength。
【It reflects v8::TypedArray::kMaxLength under the hood.】
此值也可用作 buffer.kMaxLength。
【This value is also available as buffer.kMaxLength.】
buffer.constants.MAX_STRING_LENGTH#>
- 类型: <integer> 单个
string实例允许的最大长度。
表示 string 原始类型可以拥有的最大 length,以 UTF-16 代码单元计算。
【Represents the largest length that a string primitive can have, counted
in UTF-16 code units.】
此值可能取决于正在使用的 JS 引擎。
【This value may depend on the JS engine that is being used.】
Buffer.from()、Buffer.alloc() 和 Buffer.allocUnsafe()#>
【Buffer.from(), Buffer.alloc(), and Buffer.allocUnsafe()】
在 Node.js 6.0.0 之前的版本中,Buffer 实例是使用 Buffer 构造函数创建的,该函数会根据提供的参数不同而以不同的方式分配返回的 Buffer:
【In versions of Node.js prior to 6.0.0, Buffer instances were created using the
Buffer constructor function, which allocates the returned Buffer
differently based on what arguments are provided:】
- 将一个数字作为第一个参数传递给
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,该Buffer与给定的数组缓冲区共享分配的内存。
由于 new Buffer() 的行为取决于第一个参数的类型,当没有进行参数验证或 Buffer 初始化时,可能会在应用中无意中引入安全性和可靠性问题。
【Because the behavior of new Buffer() is different depending on the type of the
first argument, security and reliability issues can be inadvertently introduced
into applications when argument validation or Buffer initialization is not
performed.】
例如,如果攻击者能够让应用在期望接收字符串的地方收到一个数字,应用可能会调用 new Buffer(100) 而不是 new Buffer("100"),导致它分配一个 100 字节的缓冲区,而不是分配一个内容为 "100" 的 3 字节缓冲区。这通常可以通过 JSON API 调用实现。由于 JSON 区分数字和字符串类型,它允许在通常编写不够严格验证输入的应用中注入数字,而这些应用可能总是期望接收到字符串。在 Node.js 8.0.0 之前,这个 100 字节的缓冲区可能包含任意已有的内存数据,因此可能被用来向远程攻击者暴露内存中的机密信息。自 Node.js 8.0.0 以来,内存泄露已不再可能,因为数据会被填充为零。然而,其他攻击仍然可能,例如导致服务器分配非常大的缓冲区,从而导致性能下降或在内存耗尽时崩溃。
【For example, if an attacker can cause an application to receive a number where
a string is expected, the application may call new Buffer(100)
instead of new Buffer("100"), leading it to allocate a 100 byte buffer instead
of allocating a 3 byte buffer with content "100". This is commonly possible
using JSON API calls. Since JSON distinguishes between numeric and string types,
it allows injection of numbers where a naively written application that does not
validate its input sufficiently might expect to always receive a string.
Before Node.js 8.0.0, the 100 byte buffer might contain
arbitrary pre-existing in-memory data, so may be used to expose in-memory
secrets to a remote attacker. Since Node.js 8.0.0, exposure of memory cannot
occur because the data is zero-filled. However, other attacks are still
possible, such as causing very large buffers to be allocated by the server,
leading to performance degradation or crashing on memory exhaustion.】
为了使创建 Buffer 实例更可靠、减少错误,new Buffer() 构造函数的各种形式已被废弃,并被单独的 Buffer.from()、Buffer.alloc() 和 Buffer.allocUnsafe() 方法取代。
【To make the creation of Buffer instances more reliable and less error-prone,
the various forms of the new Buffer() constructor have been deprecated
and replaced by separate Buffer.from(), Buffer.alloc(), and
Buffer.allocUnsafe() methods.】
开发者应该将所有现有的 new Buffer() 构造函数的使用迁移到这些新的 API 之一。
【Developers should migrate all existing uses of the new Buffer() constructors
to one of these new APIs.】
Buffer.from(array)返回一个新的Buffer,其中 包含所提供字节的副本。Buffer.from(arrayBuffer[, byteOffset[, length]])会返回一个新的Buffer,该Buffer与给定的 <ArrayBuffer> 共享相同的分配内存。Buffer.from(buffer)返回一个新的Buffer,其中 包含 给定Buffer内容的副本。[Buffer.from(string[, encoding])][Buffer.from(string)]返回一个新的Buffer,该Buffer包含提供字符串的副本。[Buffer.alloc(size[, fill[, encoding]])][Buffer.alloc()]返回一个指定大小的新初始化Buffer。该方法比Buffer.allocUnsafe(size)慢,但保证新创建的Buffer实例永远不会包含可能敏感的旧数据。如果size不是数字,将抛出TypeError。Buffer.allocUnsafe(size)和Buffer.allocUnsafeSlow(size)各自返回一个指定size的新未初始化Buffer。由于Buffer是未初始化的,分配的内存段可能包含旧数据,这些数据可能是敏感的。
Buffer 实例由 Buffer.allocUnsafe()、Buffer.from(string)、Buffer.concat() 和 Buffer.from(array) 返回时,如果 size 小于或等于 Buffer.poolSize 的一半,可能 会从共享内部内存池分配。Buffer.allocUnsafeSlow() 返回的实例 永远 不会使用共享内部内存池。
--zero-fill-buffers 命令行选项#>
【The --zero-fill-buffers command-line option】
可以使用 --zero-fill-buffers 命令行选项启动 Node.js,以便默认情况下所有新分配的 Buffer 实例在创建时都会填充为零。如果不使用该选项,使用 Buffer.allocUnsafe()、Buffer.allocUnsafeSlow() 和 new SlowBuffer(size) 创建的缓冲区不会被填充为零。使用此标志可能会对性能产生可测量的负面影响。只有在需要确保新分配的 Buffer 实例不包含可能敏感的旧数据时,才使用 --zero-fill-buffers 选项。
【Node.js can be started using the --zero-fill-buffers command-line option to
cause all newly-allocated Buffer instances to be zero-filled upon creation by
default. Without the option, buffers created with Buffer.allocUnsafe(),
Buffer.allocUnsafeSlow(), and new SlowBuffer(size) are not zero-filled.
Use of this flag can have a measurable negative impact on performance. Use the
--zero-fill-buffers option only when necessary to enforce that newly allocated
Buffer instances cannot contain old data that is potentially sensitive.】
$ node --zero-fill-buffers
> Buffer.allocUnsafe(5);
<Buffer 00 00 00 00 00>
Buffer.allocUnsafe() 和 Buffer.allocUnsafeSlow() 为什么被称为“不安全”的?#>
【What makes Buffer.allocUnsafe() and Buffer.allocUnsafeSlow() "unsafe"?】
在调用 Buffer.allocUnsafe() 和 Buffer.allocUnsafeSlow() 时,分配的内存段是 未初始化 的(未被清零)。虽然这种设计使内存分配非常快速,但已分配的内存段可能包含潜在敏感的旧数据。如果使用 Buffer.allocUnsafe() 创建 Buffer 时未 完全 覆盖内存,当读取 Buffer 内存时,这些旧数据可能会被泄漏。
【When calling Buffer.allocUnsafe() and Buffer.allocUnsafeSlow(), the
segment of allocated memory is uninitialized (it is not zeroed-out). While
this design makes the allocation of memory quite fast, the allocated segment of
memory might contain old data that is potentially sensitive. Using a Buffer
created by Buffer.allocUnsafe() without completely overwriting the
memory can allow this old data to be leaked when the Buffer memory is read.】
虽然使用 Buffer.allocUnsafe() 确实有明显的性能优势,但必须格外小心,以避免在应用中引入安全漏洞。
【While there are clear performance advantages to using
Buffer.allocUnsafe(), extra care must be taken in order to avoid
introducing security vulnerabilities into an application.】