- 断言测试
- 异步上下文跟踪
- 异步钩子
- 缓冲(Buffer)
- C++ 插件
- 使用 Node-API 的 C/C++ 插件
- C++ 嵌入 Node环境
- 子进程(Child processes)
- 集群(Cluster)
- 命令行选项
- 控制台(Console)
- 核心包(Corepack)
- 加密(Crypto)
- 调试器(Debugger)
- 已弃用的 API
- 诊断通道(Diagnostics Channel)
- 域名系统(DNS)
- 域(Domain)
- 错误(Errors)
- 事件(Events)
- 文件系统(File system)
- 全局变量(Globals)
- HTTP
- HTTP/2
- HTTPS
- 检查器(Inspector)
- 国际化
- 模块:CommonJS 模块
- 模块:ECMAScript 模块
- 模块:
node:moduleAPI - 模块:packages 模块
- 网络(Net)
- 系统(OS)
- 路径(Path)
- 性能挂钩(Performance hooks)
- 性能挂钩(Permissions)
- 进程(Process)
- Punycode 国际化域名编码
- 查询字符串(Query strings)
- 命令行库(Readline)
- REPL 交互式编程环境
- 诊断报告
- 单个可执行应用程序
- Stream 流
- 字符串解码器
- 单元测试
- 定时器(Timers)
- 传输层安全/SSL
- 跟踪事件
- TTY
- UDP/数据报
- URL
- 实用程序
- V8
- 虚拟机
- WebAssembly
- Web加密 API(Web Crypto API)
- 网络流 API(Web Streams API)
- 工作线程(Worker threads)
- zlib
Node.js v18.18.2 文档
- Node.js v18.18.2
-
►
目录
- Buffer
- Buffers and character encodings
- Buffers and TypedArrays
- Buffers and iteration
- Class:
Blob - Class:
Buffer- Static method:
Buffer.alloc(size[, fill[, encoding]]) - Static method:
Buffer.allocUnsafe(size) - Static method:
Buffer.allocUnsafeSlow(size) - Static method:
Buffer.byteLength(string[, encoding]) - Static method:
Buffer.compare(buf1, buf2) - Static method:
Buffer.concat(list[, totalLength]) - Static method:
Buffer.copyBytesFrom(view[, offset[, length]]) - Static method:
Buffer.from(array) - Static method:
Buffer.from(arrayBuffer[, byteOffset[, length]]) - Static method:
Buffer.from(buffer) - Static method:
Buffer.from(object[, offsetOrEncoding[, length]]) - Static method:
Buffer.from(string[, encoding]) - Static method:
Buffer.isBuffer(obj) - Static method:
Buffer.isEncoding(encoding) - Class property:
Buffer.poolSize buf[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])
- Static method:
- Class:
File node:buffermodule APIsBuffer.from(),Buffer.alloc(), andBuffer.allocUnsafe()
- Buffer
-
►
索引
- Assertion testing
- Asynchronous context tracking
- Async hooks
- Buffer
- C++ addons
- C/C++ addons with Node-API
- C++ embedder API
- Child processes
- Cluster
- Command-line options
- Console
- Corepack
- Crypto
- Debugger
- Deprecated APIs
- Diagnostics Channel
- DNS
- Domain
- Errors
- Events
- File system
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- Internationalization
- Modules: CommonJS modules
- Modules: ECMAScript modules
- Modules:
node:moduleAPI - Modules: Packages
- Net
- 系统(OS)
- 路径(Path)
- Performance hooks
- Permissions
- 进程(Process)
- Punycode
- Query strings
- 命令行库(Readline)
- REPL 交互式编程环境
- Report
- Single executable applications
- Stream
- String decoder
- Test runner
- Timers
- TLS/SSL
- Trace events
- TTY
- UDP/datagram
- URL
- Utilities
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- Worker threads
- Zlib
- ► 其他版本
- ► 选项
目录
- 缓冲
- 缓冲区和字符编码
- 缓冲区和 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.poolSize buf[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()
缓冲#
源代码: lib/buffer.js
Buffer对象用于表示固定长度的字节序列。许多 Node.js API 支持Buffer。
Buffer类是 JavaScript 的Uint8Array类的子类,并使用涵盖其他用例的方法对其进行了扩展。只要支持{{{ QnVmZmVy}} } ,Node.js API 就接受普通的Uint8Array 。
虽然Buffer类在全局范围内可用,但仍然建议通过 import 或 require 语句显式引用它。
import { Buffer } from 'node:buffer';
// Creates a zero-filled Buffer of length 10.
const buf1 = Buffer.alloc(10);
// Creates a Buffer of length 10,
// filled with bytes which all have the value `1`.
const buf2 = Buffer.alloc(10, 1);
// Creates an uninitialized buffer of length 10.
// This is faster than calling Buffer.alloc() but the returned
// Buffer instance might contain old data that needs to be
// overwritten using fill(), write(), or other functions that fill the Buffer's
// contents.
const buf3 = Buffer.allocUnsafe(10);
// Creates a Buffer containing the bytes [1, 2, 3].
const buf4 = Buffer.from([1, 2, 3]);
// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
// are all truncated using `(value & 255)` to fit into the range 0–255.
const buf5 = Buffer.from([257, 257.5, -255, '1']);
// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
// [116, 195, 169, 115, 116] (in decimal notation)
const buf6 = Buffer.from('tést');
// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
const buf7 = Buffer.from('tést', 'latin1');const { Buffer } = require('node:buffer');
// Creates a zero-filled Buffer of length 10.
const buf1 = Buffer.alloc(10);
// Creates a Buffer of length 10,
// filled with bytes which all have the value `1`.
const buf2 = Buffer.alloc(10, 1);
// Creates an uninitialized buffer of length 10.
// This is faster than calling Buffer.alloc() but the returned
// Buffer instance might contain old data that needs to be
// overwritten using fill(), write(), or other functions that fill the Buffer's
// contents.
const buf3 = Buffer.allocUnsafe(10);
// Creates a Buffer containing the bytes [1, 2, 3].
const buf4 = Buffer.from([1, 2, 3]);
// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
// are all truncated using `(value & 255)` to fit into the range 0–255.
const buf5 = Buffer.from([257, 257.5, -255, '1']);
// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
// [116, 195, 169, 115, 116] (in decimal notation)
const buf6 = Buffer.from('tést');
// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
const buf7 = Buffer.from('tést', 'latin1');
缓冲区和字符编码#
当在Buffer和字符串之间转换时,可以指定字符编码。如果未指定字符编码,则默认使用 UTF-8。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('hello world', 'utf8');
console.log(buf.toString('hex'));
// Prints: 68656c6c6f20776f726c64
console.log(buf.toString('base64'));
// Prints: aGVsbG8gd29ybGQ=
console.log(Buffer.from('fhqwhgads', 'utf8'));
// Prints: <Buffer 66 68 71 77 68 67 61 64 73>
console.log(Buffer.from('fhqwhgads', 'utf16le'));
// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>const { Buffer } = require('node:buffer');
const buf = Buffer.from('hello world', 'utf8');
console.log(buf.toString('hex'));
// Prints: 68656c6c6f20776f726c64
console.log(buf.toString('base64'));
// Prints: aGVsbG8gd29ybGQ=
console.log(Buffer.from('fhqwhgads', 'utf8'));
// Prints: <Buffer 66 68 71 77 68 67 61 64 73>
console.log(Buffer.from('fhqwhgads', 'utf16le'));
// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>
Node.js 缓冲区接受它们收到的编码字符串的所有大小写变化。例如,UTF-8 可以指定为'utf8'、'UTF8'或'uTf8'。
Node.js 目前支持的字符编码如下:
-
'utf8'(别名:'utf-8'):多字节编码的 Unicode 字符。许多网页和其他文档格式使用UTF-8。这是默认的字符编码。将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称为编码。
Node.js 还支持以下二进制到文本的编码。对于二进制到文本的编码,命名约定是相反的:将
Buffer转换为字符串通常称为编码,将字符串转换为Buffer称为解码。
-
'base64':Base64编码。当从字符串创建Buffer时,此编码还将正确接受RFC 4648 第 5 节中指定的“URL 和文件名安全字母表” 。Base64 编码字符串中包含的空白字符(例如空格、制表符和换行符)将被忽略。 -
'base64url':RFC 4648 第 5 节中指定的 base64url编码。当从字符串创建Buffer时,此编码也将正确接受常规的 Base64 编码字符串。将Buffer编码为字符串时,此编码将省略填充。 -
'hex':将每个字节编码为两个十六进制字符。当解码不完全由偶数个十六进制字符组成的字符串时,可能会发生数据截断。请参阅下面的示例。
还支持以下旧字符编码:
-
'ascii':仅适用于 7 位ASCII数据。将字符串编码为Buffer时,这相当于使用'latin1'。将Buffer解码 为字符串时,使用此编码将在解码为'latin1'之前另外取消设置每个字节的最高位。一般来说,没有理由使用这种编码,因为'utf8'(或者,如果已知数据始终仅是 ASCII,则'latin1')将是更好的选择编码或解码纯 ASCII 文本。提供它只是为了兼容旧版本。 -
'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'编码可能会错误地解码字符。
缓冲区和 TypedArray#
Buffer实例也是 JavaScript Uint8Array和TypedArray
实例。所有TypedArray方法均可在Buffer上使用。然而,Buffer API 和
TypedArray API 之间存在细微的不兼容性。
尤其:
- { {{VHlwZWRBcnJheS5wcm90b3R5cGUuc2xpY2UoKQ==}}}创建了
TypedArray部分的副本,而Buffer.prototype.slice()在现有的{{{QnVmZmVy}上创建了一个视图}} 无需复制。这种行为可能会令人惊讶,并且仅是为了旧版兼容性而存在。TypedArray.prototype.subarray()可用于在Buffer和其他{{{VHlwZWRBcnJheQ==}上实现Buffer.prototype.slice()的行为}} s 并且应该是首选。 buf.toString()与其等效的TypedArray不兼容。- 许多方法(例如
buf.indexOf())支持附加参数。
有两种方法可以从Buffer 创建新的TypedArray实例:
- 将
Buffer传递给TypedArray构造函数将复制Buffer的内容,解释为整数数组,而不是目标的字节序列类型。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4]);
const uint32array = new Uint32Array(buf);
console.log(uint32array);
// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3, 4]);
const uint32array = new Uint32Array(buf);
console.log(uint32array);
// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]
- 传递
Buffer的底层ArrayBuffer将创建一个 与Buffer共享内存的{ {{ VHlwZWRBcnJheQ==}}}。
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 ]
通过使用{ { {VHlwZWRBcnJheQ==}}}对象的.buffer属性以同样的方式。在这种情况下,Buffer.from()
的行为类似于new Uint8Array() 。
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
// Copies the contents of `arr`.
const buf1 = Buffer.from(arr);
// Shares memory with `arr`.
const buf2 = Buffer.from(arr.buffer);
console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 a0 0f>
arr[1] = 6000;
console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 70 17>const { Buffer } = require('node:buffer');
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
// Copies the contents of `arr`.
const buf1 = Buffer.from(arr);
// Shares memory with `arr`.
const buf2 = Buffer.from(arr.buffer);
console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 a0 0f>
arr[1] = 6000;
console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 70 17>
当使用TypedArray的.buffer 创建 Buffer时,可以仅使用底层{{{QXJyYXlCdWZmZXI=}的一部分}}通过传入
byteOffset和length参数。
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()和{ {{VHlwZWRBcnJheS5mcm9tKCk=}}}具有不同的签名和实现。具体来说,TypedArray变体接受第二个参数,该参数是在类型化数组的每个元素上调用的映射函数:
TypedArray.from(source[, mapFn[, thisArg]])
然而, Buffer.from()方法不支持使用映射函数:
缓冲区和迭代#
可以使用for..of语法迭代 Buffer实例:
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3]);
for (const b of buf) {
console.log(b);
}
// Prints:
// 1
// 2
// 3const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3]);
for (const b of buf) {
console.log(b);
}
// Prints:
// 1
// 2
// 3
此外,buf.values()、buf.keys()和
buf.entries()方法可用于创建迭代器。
类:Blob#
{ {{QmxvYg==}}}封装了不可变的原始数据,可以在多个工作线程之间安全地共享。
new buffer.Blob([sources[, options]])#
sources<字符串[]> | <数组缓冲区[]> | <TypedArray[]> | <数据视图[]> | <Blob[]>字符串数组、<ArrayBuffer>、<TypedArray>、<DataView>或<Blob>对象或此类对象的任意组合,将存储在Blob中。options<对象>
创建一个新的Blob对象,其中包含给定源的串联。
<ArrayBuffer>、<TypedArray>、<DataView>和<Buffer>源被复制到“Blob”中,因此可以在创建“Blob”后安全地进行修改。
字符串源被编码为 UTF-8 字节序列并复制到 Blob 中。每个字符串部分中不匹配的代理对将被 Unicode U+FFFD 替换字符替换。
blob.arrayBuffer()#
- 返回:< Promise >
返回一个 Promise ,该 Promise 通过包含Blob数据副本的<ArrayBuffer>来实现。
blob.size#
Blob的总大小(以字节为单位)。
blob.slice([start[, end[, type]]])#
start<number>起始索引。end<number>结束索引。type<string>新的Blob的内容类型
创建并返回一个新的Blob,其中包含此Blob对象数据的子集。原始的Blob没有改变。
blob.stream()#
- 返回:<可读流>
返回一个新的ReadableStream ,允许读取Blob的内容。
blob.text()#
- 返回:< Promise >
返回一个 Promise ,该 Promise 将Blob的内容解码为 UTF-8 字符串。
blob.type#
- 类型:<字符串>
Blob的内容类型。
Blob对象和MessageChannel#
创建<Blob>对象后,可以通过MessagePort将其发送到多个目的地,而无需传输或立即复制数据。
仅当调用arrayBuffer()或text()方法时,才会复制Blob包含的数据。
import { Blob } from 'node:buffer';
import { setTimeout as delay } from 'node:timers/promises';
const blob = new Blob(['hello there']);
const mc1 = new MessageChannel();
const mc2 = new MessageChannel();
mc1.port1.onmessage = async ({ data }) => {
console.log(await data.arrayBuffer());
mc1.port1.close();
};
mc2.port1.onmessage = async ({ data }) => {
await delay(1000);
console.log(await data.arrayBuffer());
mc2.port1.close();
};
mc1.port2.postMessage(blob);
mc2.port2.postMessage(blob);
// The Blob is still usable after posting.
blob.text().then(console.log);const { Blob } = require('node:buffer');
const { setTimeout: delay } = require('node:timers/promises');
const blob = new Blob(['hello there']);
const mc1 = new MessageChannel();
const mc2 = new MessageChannel();
mc1.port1.onmessage = async ({ data }) => {
console.log(await data.arrayBuffer());
mc1.port1.close();
};
mc2.port1.onmessage = async ({ data }) => {
await delay(1000);
console.log(await data.arrayBuffer());
mc2.port1.close();
};
mc1.port2.postMessage(blob);
mc2.port2.postMessage(blob);
// The Blob is still usable after posting.
blob.text().then(console.log);
类别:Buffer#
Buffer类是直接处理二进制数据的全局类型。它可以通过多种方式构建。
静态方法:Buffer.alloc(size[, fill[, encoding]])#
size<integer>新的Buffer的所需长度。fill<字符串> | <缓冲区> | <Uint8Array> | <integer>预填充新的Buffer的值 。默认值:0。encoding<string>如果fill是字符串,则这是其编码。 默认值:'utf8'。
分配新的Buffer size字节。如果fill为undefined,则
Buffer将被零填充。
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(5);
console.log(buf);
// Prints: <Buffer 00 00 00 00 00>const { Buffer } = require('node:buffer');
const buf = Buffer.alloc(5);
console.log(buf);
// Prints: <Buffer 00 00 00 00 00>
如果size大于
buffer.constants.MAX_LENGTH或小于 0,
则抛出ERR_OUT_OF_RANGE 。
如果指定了fill ,则分配的Buffer将通过调用buf.fill(fill)进行初始化
。
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(5, 'a');
console.log(buf);
// Prints: <Buffer 61 61 61 61 61>const { Buffer } = require('node:buffer');
const buf = Buffer.alloc(5, 'a');
console.log(buf);
// Prints: <Buffer 61 61 61 61 61>
如果同时指定了fill和encoding ,则分配的Buffer将通过调用buf.fill(fill, encoding)进行初始化。
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
console.log(buf);
// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>const { Buffer } = require('node:buffer');
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
console.log(buf);
// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
调用Buffer.alloc()可能比替代的
Buffer.allocUnsafe()慢得多,但可确保新创建的Buffer实例内容永远不会包含来自先前分配的敏感数据,包括数据可能尚未分配给Buffer s。
如果size不是数字,则会抛出 TypeError 。
静态方法:Buffer.allocUnsafe(size)#
size<integer>新的Buffer的所需长度。
分配新的Buffer size字节。如果size大于
buffer.constants.MAX_LENGTH或小于 0,
则抛出ERR_OUT_OF_RANGE 。
以这种方式创建的Buffer实例的底层内存未初始化。新创建的Buffer的内容未知,
可能包含敏感数据。请使用Buffer.alloc()来用零初始化
Buffer实例。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(10);
console.log(buf);
// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
buf.fill(0);
console.log(buf);
// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(10);
console.log(buf);
// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
buf.fill(0);
console.log(buf);
// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
如果size不是数字,则会抛出 TypeError 。
Buffer模块预分配大小为Buffer.poolSize的内部Buffer实例,用作快速分配新的
Buffer的池仅当size小于或等于Buffer.poolSize >> 1(Buffer.poolSize的下限除以 2)。
使用此预分配的内部内存池是调用Buffer.alloc(size, fill)与Buffer.allocUnsafe(size).fill(fill)之间的关键区别。具体来说,Buffer.alloc(size, fill)永远不会使用内部Buffer
池,而Buffer.allocUnsafe(size).fill(fill) 将使用内部
Buffer池如果size小于或等于一半Buffer.poolSize。这种差异很微妙,但当应用程序需要Buffer.allocUnsafe()提供的额外性能时,差异可能很重要。
静态方法:Buffer.allocUnsafeSlow(size)#
size<integer>新的Buffer的所需长度。
分配新的Buffer size字节。如果size大于
buffer.constants.MAX_LENGTH或小于 0,
则抛出ERR_OUT_OF_RANGE 。如果size为 0 ,则创建零长度Buffer。
以这种方式创建的Buffer实例的底层内存未初始化。新创建的Buffer的内容未知,
可能包含敏感数据。使用buf.fill(0)将此类Buffer实例初始化为零。
当使用Buffer.allocUnsafe()分配新的Buffer实例时,4 KiB 以下的分配将从单个预分配的Buffer中切片。这允许应用程序避免创建许多单独分配的Buffer实例的垃圾收集开销。这种方法无需跟踪和清理尽可能多的单独的ArrayBuffer对象,从而提高性能和内存使用率。
但是,如果开发人员可能需要在不确定的时间内保留池中的一小块内存,则可能适合使用 Buffer.allocUnsafeSlow()然后复制出相关位。
import { Buffer } from 'node:buffer';
// Need to keep around a few small chunks of memory.
const store = [];
socket.on('readable', () => {
let data;
while (null !== (data = readable.read())) {
// Allocate for retained data.
const sb = Buffer.allocUnsafeSlow(10);
// Copy the data into the new allocation.
data.copy(sb, 0, 0, 10);
store.push(sb);
}
});const { Buffer } = require('node:buffer');
// Need to keep around a few small chunks of memory.
const store = [];
socket.on('readable', () => {
let data;
while (null !== (data = readable.read())) {
// Allocate for retained data.
const sb = Buffer.allocUnsafeSlow(10);
// Copy the data into the new allocation.
data.copy(sb, 0, 0, 10);
store.push(sb);
}
});
如果size不是数字,则会抛出 TypeError 。
静态方法:Buffer.byteLength(string[, encoding])#
string<字符串> | <缓冲区> | <类型化数组> | <数据视图> | <数组缓冲区> | <SharedArrayBuffer>用于计算长度的值。encoding<string>如果string是字符串,则这是其编码。 默认值:'utf8'。- 返回:<integer>
string中包含的字节数。
返回使用encoding编码时字符串的字节长度。这与String.prototype.length不同,后者不考虑用于将字符串转换为字节的编码。
对于'base64'、'base64url'和'hex',此函数假定输入有效。对于包含非 Base64/hex 编码数据(例如空格)的字符串,返回值可能大于从字符串创建的Buffer的长度。
import { Buffer } from 'node:buffer';
const str = '\u00bd + \u00bc = \u00be';
console.log(`${str}: ${str.length} characters, ` +
`${Buffer.byteLength(str, 'utf8')} bytes`);
// Prints: ½ + ¼ = ¾: 9 characters, 12 bytesconst { Buffer } = require('node:buffer');
const str = '\u00bd + \u00bc = \u00be';
console.log(`${str}: ${str.length} characters, ` +
`${Buffer.byteLength(str, 'utf8')} bytes`);
// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
当string为Buffer / DataView / {{ {VHlwZWRBcnJheQ==}}} / ArrayBuffer /
SharedArrayBuffer ,
返回.byteLength报告的字节长度。
静态方法:Buffer.compare(buf1, buf2)#
buf1<缓冲区> | <Uint8Array>buf2<缓冲区> | <Uint8Array>- 返回:<integer>
-1、0或1,具体取决于比较结果。有关详细信息,请参阅buf.compare()。
将buf1与buf2进行比较,通常用于对
Buffer实例的数组进行排序。这相当于调用
buf1.compare(buf2)。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('1234');
const buf2 = Buffer.from('0123');
const arr = [buf1, buf2];
console.log(arr.sort(Buffer.compare));
// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
// (This result is equal to: [buf2, buf1].)const { Buffer } = require('node:buffer');
const buf1 = Buffer.from('1234');
const buf2 = Buffer.from('0123');
const arr = [buf1, buf2];
console.log(arr.sort(Buffer.compare));
// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
// (This result is equal to: [buf2, buf1].)
静态方法:Buffer.concat(list[, totalLength])#
list<缓冲区[]> | <Uint8Array[]>要连接的Buffer或Uint8Array实例的列表。totalLength<整数> 连接时list中的Buffer实例的总长度。- 返回:<缓冲区>
返回一个新的Buffer ,它是将list
中的所有Buffer实例连接在一起的结果。
如果列表没有项目,或者totalLength为 0,则返回新的零长度
Buffer 。
如果未提供totalLength ,则通过将 list中的Buffer实例的长度相加来计算。
如果提供了totalLength ,则将其强制为无符号整数。如果list中的Buffer的组合长度超过totalLength,则结果将被截断为totalLength。
import { Buffer } from 'node:buffer';
// Create a single `Buffer` from a list of three `Buffer` instances.
const buf1 = Buffer.alloc(10);
const buf2 = Buffer.alloc(14);
const buf3 = Buffer.alloc(18);
const totalLength = buf1.length + buf2.length + buf3.length;
console.log(totalLength);
// Prints: 42
const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
console.log(bufA);
// Prints: <Buffer 00 00 00 00 ...>
console.log(bufA.length);
// Prints: 42const { Buffer } = require('node:buffer');
// Create a single `Buffer` from a list of three `Buffer` instances.
const buf1 = Buffer.alloc(10);
const buf2 = Buffer.alloc(14);
const buf3 = Buffer.alloc(18);
const totalLength = buf1.length + buf2.length + buf3.length;
console.log(totalLength);
// Prints: 42
const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
console.log(bufA);
// Prints: <Buffer 00 00 00 00 ...>
console.log(bufA.length);
// Prints: 42
Buffer.concat()也可以像Buffer.allocUnsafe()一样使用内部Buffer池
。
静态方法:Buffer.copyBytesFrom(view[, offset[, length]])#
view<TypedArray>要复制的<TypedArray> 。offset<integer>view内的起始偏移量。默认值::0。length<integer>要复制的view中的元素数量。 默认值:view.length - offset。
将view的底层内存复制到新的Buffer中。
const u16 = new Uint16Array([0, 0xffff]);
const buf = Buffer.copyBytesFrom(u16, 1, 1);
u16[1] = 0;
console.log(buf.length); // 2
console.log(buf[0]); // 255
console.log(buf[1]); // 255
静态方法:Buffer.from(array)#
array<整数[]>
使用0 – 255范围内的字节array分配新的Buffer 。该范围之外的数组条目将被截断以适应该范围。
import { Buffer } from 'node:buffer';
// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);const { Buffer } = require('node:buffer');
// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
如果array是一个类似Array 的对象(即具有类型为number 的length属性的对象),则它是除非它是Buffer或Uint8Array ,否则将其视为数组。这意味着所有其他TypedArray变体都被视为
Array。要从支持TypedArray的字节创建 Buffer ,请使用
Buffer.copyBytesFrom()。
如果array不是Array或适合Buffer.from()变体的其他类型,则会抛出 TypeError。
Buffer.from(array)和Buffer.from(string)也可以像{{{QnVmZmVyLmFsbG9jVW5zYWZlKCk=}} } 一样使用内部
Buffer池。
静态方法:Buffer.from(arrayBuffer[, byteOffset[, length]])#
arrayBuffer<ArrayBuffer> | <SharedArrayBuffer> { {{QXJyYXlCdWZmZmZXI=}}}、SharedArrayBuffer,例如TypedArray的{{{LmJ1ZmZlcg==}} }属性 。byteOffset<integer>要公开的第一个字节的索引。默认值:0。length<integer>要公开的字节数。 默认值:arrayBuffer.byteLength - byteOffset。
这将创建ArrayBuffer的视图,而无需复制底层内存。例如,当传递对TypedArray实例的{{{LmJ1ZmZlcg==}} }属性的
引用时,新创建的Buffer将与实例共享相同的分配内存。TypedArray的底层ArrayBuffer。
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
// Shares memory with `arr`.
const buf = Buffer.from(arr.buffer);
console.log(buf);
// Prints: <Buffer 88 13 a0 0f>
// Changing the original Uint16Array changes the Buffer also.
arr[1] = 6000;
console.log(buf);
// Prints: <Buffer 88 13 70 17>const { Buffer } = require('node:buffer');
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
// Shares memory with `arr`.
const buf = Buffer.from(arr.buffer);
console.log(buf);
// Prints: <Buffer 88 13 a0 0f>
// Changing the original Uint16Array changes the Buffer also.
arr[1] = 6000;
console.log(buf);
// Prints: <Buffer 88 13 70 17>
可选的byteOffset和length参数指定arrayBuffer内将由Buffer共享的内存范围。
import { Buffer } from 'node:buffer';
const ab = new ArrayBuffer(10);
const buf = Buffer.from(ab, 0, 2);
console.log(buf.length);
// Prints: 2const { Buffer } = require('node:buffer');
const ab = new ArrayBuffer(10);
const buf = Buffer.from(ab, 0, 2);
console.log(buf.length);
// Prints: 2
如果arrayBuffer不是ArrayBuffer或
SharedArrayBuffer或其他适合{{{QnVmZmVyLmZyb20o肯Q ==}}}
变体。
重要的是要记住,后备ArrayBuffer可以覆盖超出TypedArray视图边界的内存范围。使用TypedArray的buffer属性创建的新
Buffer可能会超出TypedArray的范围:
import { Buffer } from 'node:buffer';
const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
console.log(arrA.buffer === arrB.buffer); // true
const buf = Buffer.from(arrB.buffer);
console.log(buf);
// Prints: <Buffer 63 64 65 66>const { Buffer } = require('node:buffer');
const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
console.log(arrA.buffer === arrB.buffer); // true
const buf = Buffer.from(arrB.buffer);
console.log(buf);
// Prints: <Buffer 63 64 65 66>
静态方法:Buffer.from(buffer)#
buffer<缓冲区> | <Uint8Array>要从中复制数据的现有Buffer或Uint8Array。
将传递的buffer数据复制到新的Buffer实例上。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);
buf1[0] = 0x61;
console.log(buf1.toString());
// Prints: auffer
console.log(buf2.toString());
// Prints: bufferconst { Buffer } = require('node:buffer');
const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);
buf1[0] = 0x61;
console.log(buf1.toString());
// Prints: auffer
console.log(buf2.toString());
// Prints: buffer
如果buffer不是Buffer或适合Buffer.from()变体的其他类型,则会抛出 TypeError 。
静态方法:Buffer.from(object[, offsetOrEncoding[, length]])#
object<Object>支持Symbol.toPrimitive或valueOf()的对象。offsetOrEncoding<整数> | <string>字节偏移量或编码。length<整数>长度。
对于valueOf()函数返回值不严格等于
object的对象,返回Buffer.from(object.valueOf(), offsetOrEncoding, length)。
import { Buffer } from 'node:buffer';
const buf = Buffer.from(new String('this is a test'));
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>const { Buffer } = require('node:buffer');
const buf = Buffer.from(new String('this is a test'));
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
对于支持Symbol.toPrimitive的对象,返回
Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding)。
import { Buffer } from 'node:buffer';
class Foo {
[Symbol.toPrimitive]() {
return 'this is a test';
}
}
const buf = Buffer.from(new Foo(), 'utf8');
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>const { Buffer } = require('node:buffer');
class Foo {
[Symbol.toPrimitive]() {
return 'this is a test';
}
}
const buf = Buffer.from(new Foo(), 'utf8');
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
如果object没有提到的方法或者不是适合Buffer.from()变体的其他类型,则会抛出 TypeError。
静态方法:Buffer.from(string[, encoding])#
创建一个包含string的新Buffer 。encoding参数标识将string转换为字节时要使用的字符编码。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('this is a tést');
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
console.log(buf1.toString());
// Prints: this is a tést
console.log(buf2.toString());
// Prints: this is a tést
console.log(buf1.toString('latin1'));
// Prints: this is a téstconst { Buffer } = require('node:buffer');
const buf1 = Buffer.from('this is a tést');
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
console.log(buf1.toString());
// Prints: this is a tést
console.log(buf2.toString());
// Prints: this is a tést
console.log(buf1.toString('latin1'));
// Prints: this is a tést
如果string不是字符串或适合Buffer.from()变体的其他类型,则会抛出 TypeError。
静态方法:Buffer.isBuffer(obj)#
如果obj是Buffer ,则返回true ,否则返回false 。
import { Buffer } from 'node:buffer';
Buffer.isBuffer(Buffer.alloc(10)); // true
Buffer.isBuffer(Buffer.from('foo')); // true
Buffer.isBuffer('a string'); // false
Buffer.isBuffer([]); // false
Buffer.isBuffer(new Uint8Array(1024)); // falseconst { Buffer } = require('node:buffer');
Buffer.isBuffer(Buffer.alloc(10)); // true
Buffer.isBuffer(Buffer.from('foo')); // true
Buffer.isBuffer('a string'); // false
Buffer.isBuffer([]); // false
Buffer.isBuffer(new Uint8Array(1024)); // false
静态方法:Buffer.isEncoding(encoding)#
如果encoding是受支持的字符编码的名称,则返回 true,否则返回 false。
import { Buffer } from 'node:buffer';
console.log(Buffer.isEncoding('utf8'));
// Prints: true
console.log(Buffer.isEncoding('hex'));
// Prints: true
console.log(Buffer.isEncoding('utf/8'));
// Prints: false
console.log(Buffer.isEncoding(''));
// Prints: falseconst { Buffer } = require('node:buffer');
console.log(Buffer.isEncoding('utf8'));
// Prints: true
console.log(Buffer.isEncoding('hex'));
// Prints: true
console.log(Buffer.isEncoding('utf/8'));
// Prints: false
console.log(Buffer.isEncoding(''));
// Prints: false
类属性:Buffer.poolSize#
- <整数> 默认值:
8192
这是用于池化的预分配内部Buffer实例的大小(以字节为单位) 。该值可以修改。
buf[index]#
index<整数>
索引运算符[index]可用于获取和设置
buf中位置index处的八位字节。这些值指的是各个字节,因此合法值范围介于0x00和0xFF(十六进制)或0和255(十进制)。
该运算符继承自Uint8Array,因此其越界访问的行为与Uint8Array相同。换句话说,当index为负或大于或等于buf.length时, buf[index]返回
undefined ,并且
{{如果index为负数或
>= buf.length ,则{YnVmW2luZGV4XSA9IHZhbHVl}}}不会修改缓冲区。
import { Buffer } from 'node:buffer';
// Copy an ASCII string into a `Buffer` one byte at a time.
// (This only works for ASCII-only strings. In general, one should use
// `Buffer.from()` to perform this conversion.)
const str = 'Node.js';
const buf = Buffer.allocUnsafe(str.length);
for (let i = 0; i < str.length; i++) {
buf[i] = str.charCodeAt(i);
}
console.log(buf.toString('utf8'));
// Prints: Node.jsconst { Buffer } = require('node:buffer');
// Copy an ASCII string into a `Buffer` one byte at a time.
// (This only works for ASCII-only strings. In general, one should use
// `Buffer.from()` to perform this conversion.)
const str = 'Node.js';
const buf = Buffer.allocUnsafe(str.length);
for (let i = 0; i < str.length; i++) {
buf[i] = str.charCodeAt(i);
}
console.log(buf.toString('utf8'));
// Prints: Node.js
buf.buffer#
- <ArrayBuffer>
创建此
Buffer对象所基于的基础ArrayBuffer对象。
不保证此ArrayBuffer与原始
Buffer完全对应。有关详细信息,请参阅buf.byteOffset上的注释。
import { Buffer } from 'node:buffer';
const arrayBuffer = new ArrayBuffer(16);
const buffer = Buffer.from(arrayBuffer);
console.log(buffer.buffer === arrayBuffer);
// Prints: trueconst { Buffer } = require('node:buffer');
const arrayBuffer = new ArrayBuffer(16);
const buffer = Buffer.from(arrayBuffer);
console.log(buffer.buffer === arrayBuffer);
// Prints: true
buf.byteOffset#
- <integer>
Buffer的底层ArrayBuffer对象的byteOffset。
当在Buffer.from(ArrayBuffer, byteOffset, length) 中设置 byteOffset时,或者有时分配小于{{{QnVmZmVyLnBv 的 Buffer时b2xTaXpl}}},缓冲区不从 a 开始基础ArrayBuffer上的零偏移。
当直接使用buf.buffer访问底层ArrayBuffffW时,这可能会导致问题,因为ArrayBuffer的其他部分可能与Buffer对象本身。
创建与Buffer共享内存的 TypedArray 对象时的一个常见问题是,在这种情况下需要正确指定byteOffset :
import { Buffer } from 'node:buffer';
// Create a buffer smaller than `Buffer.poolSize`.
const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
// When casting the Node.js Buffer to an Int8Array, use the byteOffset
// to refer only to the part of `nodeBuffer.buffer` that contains the memory
// for `nodeBuffer`.
new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);const { Buffer } = require('node:buffer');
// Create a buffer smaller than `Buffer.poolSize`.
const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
// When casting the Node.js Buffer to an Int8Array, use the byteOffset
// to refer only to the part of `nodeBuffer.buffer` that contains the memory
// for `nodeBuffer`.
new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])#
target<缓冲区> | <Uint8Array>与buf进行比较的Buffer或Uint8Array。targetStart<整数>target内开始比较的偏移量。默认值:0。targetEnd<整数>target内结束比较的偏移量(不包括在内)。默认值:target.length。sourceStart<integer>buf内开始比较的 偏移量。默认值:0。sourceEnd<integer>buf内结束比较的偏移量(不包括在内)。默认值:buf.length。- 返回:<整数>
将buf与target进行比较,并返回一个数字,指示buf按排序顺序是否
位于target之前、之后或相同。比较基于每个Buffer中的实际字节序列。
- 如果
target与buf相同,则返回0 - 如果排序时
target应位于buf之前 ,则返回1。 - 如果排序时
target应位于buf之后 ,则返回-1。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('BCD');
const buf3 = Buffer.from('ABCD');
console.log(buf1.compare(buf1));
// Prints: 0
console.log(buf1.compare(buf2));
// Prints: -1
console.log(buf1.compare(buf3));
// Prints: -1
console.log(buf2.compare(buf1));
// Prints: 1
console.log(buf2.compare(buf3));
// Prints: 1
console.log([buf1, buf2, buf3].sort(Buffer.compare));
// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
// (This result is equal to: [buf1, buf3, buf2].)const { Buffer } = require('node:buffer');
const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('BCD');
const buf3 = Buffer.from('ABCD');
console.log(buf1.compare(buf1));
// Prints: 0
console.log(buf1.compare(buf2));
// Prints: -1
console.log(buf1.compare(buf3));
// Prints: -1
console.log(buf2.compare(buf1));
// Prints: 1
console.log(buf2.compare(buf3));
// Prints: 1
console.log([buf1, buf2, buf3].sort(Buffer.compare));
// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
// (This result is equal to: [buf1, buf3, buf2].)
可选的targetStart、targetEnd、sourceStart和sourceEnd
参数可用于将比较限制为{{分别为{dGFyZ2V0}}}
和buf。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
console.log(buf1.compare(buf2, 5, 9, 0, 4));
// Prints: 0
console.log(buf1.compare(buf2, 0, 6, 4));
// Prints: -1
console.log(buf1.compare(buf2, 5, 6, 5));
// Prints: 1const { Buffer } = require('node:buffer');
const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
console.log(buf1.compare(buf2, 5, 9, 0, 4));
// Prints: 0
console.log(buf1.compare(buf2, 0, 6, 4));
// Prints: -1
console.log(buf1.compare(buf2, 5, 6, 5));
// Prints: 1
如果targetStart < 0、 sourceStart < 0、
targetEnd > target.byteLength或则抛出{ c291cmNlRW5kID4gc291cmNlLmJ5dGVMZW5ndGg=}}}。
buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])#
target<缓冲区> | <Uint8Array>要复制到的Buffer或{ {{VWludDhBcnJheQ==}}} 。targetStart<整数>target内开始写入的偏移量。默认值:0。sourceStart<integer>buf内开始复制的 偏移量。默认值:0。sourceEnd<integer>buf内停止复制的偏移量(不包括在内)。默认值:buf.length。- 返回:<integer>复制的字节数。
将数据从buf区域复制到target中的区域,即使target
内存区域与buf重叠。
TypedArray.prototype.set()执行相同的操作,并且可用于所有 TypedArray,包括 Node.js Buffer s,尽管它采用不同的函数参数。
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()#
- 返回:<迭代器>
根据buf的内容创建并返回[index, byte]对的迭代器。
import { Buffer } from 'node:buffer';
// Log the entire contents of a `Buffer`.
const buf = Buffer.from('buffer');
for (const pair of buf.entries()) {
console.log(pair);
}
// Prints:
// [0, 98]
// [1, 117]
// [2, 102]
// [3, 102]
// [4, 101]
// [5, 114]const { Buffer } = require('node:buffer');
// Log the entire contents of a `Buffer`.
const buf = Buffer.from('buffer');
for (const pair of buf.entries()) {
console.log(pair);
}
// Prints:
// [0, 98]
// [1, 117]
// [2, 102]
// [3, 102]
// [4, 101]
// [5, 114]
buf.equals(otherBuffer)#
otherBuffer<缓冲区> | <Uint8Array>与buf进行比较的Buffer或Uint8Array。- 返回:<布尔值>
如果buf和otherBuffer具有完全相同的字节,
则返回true,否则返回 false 。相当于
buf.compare(otherBuffer) === 0。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('414243', 'hex');
const buf3 = Buffer.from('ABCD');
console.log(buf1.equals(buf2));
// Prints: true
console.log(buf1.equals(buf3));
// Prints: falseconst { Buffer } = require('node:buffer');
const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('414243', 'hex');
const buf3 = Buffer.from('ABCD');
console.log(buf1.equals(buf2));
// Prints: true
console.log(buf1.equals(buf3));
// Prints: false
buf.fill(value[, offset[, end]][, encoding])#
value<字符串> | <缓冲区> | <Uint8Array> | <integer>用于填充buf的值。空值(字符串、Uint8Array、Buffer)被强制为0。offset<integer>开始填充buf之前要跳过的字节数。 默认值:0。end<integer>在何处停止填充buf(不包括在内)。默认值:buf.length。encoding<string>如果value是字符串, 则value的编码。默认值:'utf8'。- 返回:<Buffer>对
buf的引用。
用指定的value填充buf。如果未给出offset和end ,则将填充整个buf :
import { Buffer } from 'node:buffer';
// Fill a `Buffer` with the ASCII character 'h'.
const b = Buffer.allocUnsafe(50).fill('h');
console.log(b.toString());
// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
// Fill a buffer with empty string
const c = Buffer.allocUnsafe(5).fill('');
console.log(c.fill(''));
// Prints: <Buffer 00 00 00 00 00>const { Buffer } = require('node:buffer');
// Fill a `Buffer` with the ASCII character 'h'.
const b = Buffer.allocUnsafe(50).fill('h');
console.log(b.toString());
// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
// Fill a buffer with empty string
const c = Buffer.allocUnsafe(5).fill('');
console.log(c.fill(''));
// Prints: <Buffer 00 00 00 00 00>
如果value不是字符串、Buffer或整数,则它会被强制转换为 uint32 值。如果生成的整数大于255(十进制),则buf将填充为value & 255。
如果fill()操作的最终写入落在多字节字符上,则仅写入适合buf的该字符的字节:
import { Buffer } from 'node:buffer';
// Fill a `Buffer` with character that takes up two bytes in UTF-8.
console.log(Buffer.allocUnsafe(5).fill('\u0222'));
// Prints: <Buffer c8 a2 c8 a2 c8>const { Buffer } = require('node:buffer');
// Fill a `Buffer` with character that takes up two bytes in UTF-8.
console.log(Buffer.allocUnsafe(5).fill('\u0222'));
// Prints: <Buffer c8 a2 c8 a2 c8>
如果value包含无效字符,则会被截断;如果没有剩余有效的填充数据,则会抛出异常:
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(5);
console.log(buf.fill('a'));
// Prints: <Buffer 61 61 61 61 61>
console.log(buf.fill('aazz', 'hex'));
// Prints: <Buffer aa aa aa aa aa>
console.log(buf.fill('zz', 'hex'));
// Throws an exception.const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(5);
console.log(buf.fill('a'));
// Prints: <Buffer 61 61 61 61 61>
console.log(buf.fill('aazz', 'hex'));
// Prints: <Buffer aa aa aa aa aa>
console.log(buf.fill('zz', 'hex'));
// Throws an exception.
buf.includes(value[, byteOffset][, encoding])#
value<字符串> | <缓冲区> | <Uint8Array> | <整数>要搜索的内容。byteOffset<integer>在buf中开始搜索的位置。如果为负数,则从buf末尾计算偏移量。默认值:0。encoding<string>如果value是字符串,则这是其编码。 默认值:'utf8'。- 返回:<boolean>
true如果在buf中找到了value,否则为false。
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<字符串> | <缓冲区> | <Uint8Array> | <整数>要搜索的内容。byteOffset<integer>在buf中开始搜索的位置。如果为负数,则从buf末尾计算偏移量。默认值:0。encoding<string>如果value是字符串,则这是用于确定将在buf中搜索的字符串的二进制表示形式的编码 。默认值:'utf8'。- 返回:<integer> {{ {YnVm}}}中第一次出现
value的索引,或-1(如果buf不包含value。
如果value是:
- 字符串
value根据encoding中的字符编码进行解释。 Buffer或Uint8Array、value将被完整使用。要比较部分Buffer,请使用buf.subarray。- 数字
value将被解释为0和255之间的无符号 8 位整数值。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this is a buffer');
console.log(buf.indexOf('this'));
// Prints: 0
console.log(buf.indexOf('is'));
// Prints: 2
console.log(buf.indexOf(Buffer.from('a buffer')));
// Prints: 8
console.log(buf.indexOf(97));
// Prints: 8 (97 is the decimal ASCII value for 'a')
console.log(buf.indexOf(Buffer.from('a buffer example')));
// Prints: -1
console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
// Prints: 8
const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
// Prints: 4
console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
// Prints: 6const { Buffer } = require('node:buffer');
const buf = Buffer.from('this is a buffer');
console.log(buf.indexOf('this'));
// Prints: 0
console.log(buf.indexOf('is'));
// Prints: 2
console.log(buf.indexOf(Buffer.from('a buffer')));
// Prints: 8
console.log(buf.indexOf(97));
// Prints: 8 (97 is the decimal ASCII value for 'a')
console.log(buf.indexOf(Buffer.from('a buffer example')));
// Prints: -1
console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
// Prints: 8
const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
// Prints: 4
console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
// Prints: 6
如果value不是字符串、数字或Buffer,则此方法将抛出
TypeError。如果value是一个数字,它将被强制转换为有效的字节值,即 0 到 255 之间的整数。
如果byteOffset不是数字,它将被强制为数字。如果强制转换的结果是NaN或0,则将搜索整个缓冲区。此行为与String.prototype.indexOf()匹配。
import { Buffer } from 'node:buffer';
const b = Buffer.from('abcdef');
// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.indexOf(99.9));
console.log(b.indexOf(256 + 99));
// Passing a byteOffset that coerces to NaN or 0.
// Prints: 1, searching the whole buffer.
console.log(b.indexOf('b', undefined));
console.log(b.indexOf('b', {}));
console.log(b.indexOf('b', null));
console.log(b.indexOf('b', []));const { Buffer } = require('node:buffer');
const b = Buffer.from('abcdef');
// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.indexOf(99.9));
console.log(b.indexOf(256 + 99));
// Passing a byteOffset that coerces to NaN or 0.
// Prints: 1, searching the whole buffer.
console.log(b.indexOf('b', undefined));
console.log(b.indexOf('b', {}));
console.log(b.indexOf('b', null));
console.log(b.indexOf('b', []));
如果value是空字符串或空Buffer且byteOffset小于buf.length,则byteOffset将被返回。如果value为空且
byteOffset至少为buf.length,则将返回buf.length 。
buf.keys()#
- 返回:<迭代器>
创建并返回buf键(索引)的迭代器。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
for (const key of buf.keys()) {
console.log(key);
}
// Prints:
// 0
// 1
// 2
// 3
// 4
// 5const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
for (const key of buf.keys()) {
console.log(key);
}
// Prints:
// 0
// 1
// 2
// 3
// 4
// 5
buf.lastIndexOf(value[, byteOffset][, encoding])#
value<字符串> | <缓冲区> | <Uint8Array> | <整数>要搜索的内容。byteOffset<integer>在buf中开始搜索的位置。如果为负数,则从buf末尾计算偏移量。默认值:buf.length - 1。encoding<string>如果value是字符串,则这是用于确定将在buf中搜索的字符串的二进制表示形式的编码 。默认值:'utf8'。- 返回:<integer> {{ {YnVm}}}中最后一次出现
value的索引,或-1(如果buf不包含value。
与buf.indexOf()相同,只是找到了最后一次出现的value而不是第一次出现。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this buffer is a buffer');
console.log(buf.lastIndexOf('this'));
// Prints: 0
console.log(buf.lastIndexOf('buffer'));
// Prints: 17
console.log(buf.lastIndexOf(Buffer.from('buffer')));
// Prints: 17
console.log(buf.lastIndexOf(97));
// Prints: 15 (97 is the decimal ASCII value for 'a')
console.log(buf.lastIndexOf(Buffer.from('yolo')));
// Prints: -1
console.log(buf.lastIndexOf('buffer', 5));
// Prints: 5
console.log(buf.lastIndexOf('buffer', 4));
// Prints: -1
const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
// Prints: 6
console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
// Prints: 4const { Buffer } = require('node:buffer');
const buf = Buffer.from('this buffer is a buffer');
console.log(buf.lastIndexOf('this'));
// Prints: 0
console.log(buf.lastIndexOf('buffer'));
// Prints: 17
console.log(buf.lastIndexOf(Buffer.from('buffer')));
// Prints: 17
console.log(buf.lastIndexOf(97));
// Prints: 15 (97 is the decimal ASCII value for 'a')
console.log(buf.lastIndexOf(Buffer.from('yolo')));
// Prints: -1
console.log(buf.lastIndexOf('buffer', 5));
// Prints: 5
console.log(buf.lastIndexOf('buffer', 4));
// Prints: -1
const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
// Prints: 6
console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
// Prints: 4
如果value不是字符串、数字或Buffer,则此方法将抛出
TypeError。如果value是一个数字,它将被强制转换为有效的字节值,即 0 到 255 之间的整数。
如果byteOffset不是数字,它将被强制为数字。任何强制转换为NaN的参数(例如{}或undefined )都将搜索整个缓冲区。此行为与String.prototype.lastIndexOf()匹配。
import { Buffer } from 'node:buffer';
const b = Buffer.from('abcdef');
// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.lastIndexOf(99.9));
console.log(b.lastIndexOf(256 + 99));
// Passing a byteOffset that coerces to NaN.
// Prints: 1, searching the whole buffer.
console.log(b.lastIndexOf('b', undefined));
console.log(b.lastIndexOf('b', {}));
// Passing a byteOffset that coerces to 0.
// Prints: -1, equivalent to passing 0.
console.log(b.lastIndexOf('b', null));
console.log(b.lastIndexOf('b', []));const { Buffer } = require('node:buffer');
const b = Buffer.from('abcdef');
// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.lastIndexOf(99.9));
console.log(b.lastIndexOf(256 + 99));
// Passing a byteOffset that coerces to NaN.
// Prints: 1, searching the whole buffer.
console.log(b.lastIndexOf('b', undefined));
console.log(b.lastIndexOf('b', {}));
// Passing a byteOffset that coerces to 0.
// Prints: -1, equivalent to passing 0.
console.log(b.lastIndexOf('b', null));
console.log(b.lastIndexOf('b', []));
如果value是空字符串或空Buffer,则将返回 byteOffset 。
buf.length#
返回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.parent的已弃用别名。
buf.readBigInt64BE([offset])#
从指定的 offset 处的 buf读取有符号的大端 64 位整数。
从Buffer读取的整数被解释为二进制补码有符号值。
buf.readBigInt64LE([offset])#
从指定的 offset 处的 buf读取
有符号的小端 64 位整数。
从Buffer读取的整数被解释为二进制补码有符号值。
buf.readBigUInt64BE([offset])#
从指定的offset处的
buf读取无符号、大端 64 位整数。
此函数也可在readBigUint64BE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
console.log(buf.readBigUInt64BE(0));
// Prints: 4294967295nconst { Buffer } = require('node:buffer');
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
console.log(buf.readBigUInt64BE(0));
// Prints: 4294967295n
buf.readBigUInt64LE([offset])#
从指定的offset处的
buf读取无符号、小端 64 位整数。
此函数也可在readBigUint64LE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
console.log(buf.readBigUInt64LE(0));
// Prints: 18446744069414584320nconst { Buffer } = require('node:buffer');
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
console.log(buf.readBigUInt64LE(0));
// Prints: 18446744069414584320n
buf.readDoubleBE([offset])#
从指定的offset 处的 buf读取 64 位大端双精度值。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readDoubleBE(0));
// Prints: 8.20788039913184e-304const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readDoubleBE(0));
// Prints: 8.20788039913184e-304
buf.readDoubleLE([offset])#
从指定的offset 处的 buf读取 64 位小端双精度值。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readDoubleLE(0));
// Prints: 5.447603722011605e-270
console.log(buf.readDoubleLE(1));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readDoubleLE(0));
// Prints: 5.447603722011605e-270
console.log(buf.readDoubleLE(1));
// Throws ERR_OUT_OF_RANGE.
buf.readFloatBE([offset])#
从指定的offset处的 buf读取 32 位大端浮点数。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4]);
console.log(buf.readFloatBE(0));
// Prints: 2.387939260590663e-38const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3, 4]);
console.log(buf.readFloatBE(0));
// Prints: 2.387939260590663e-38
buf.readFloatLE([offset])#
从指定的offset处的 buf读取 32 位小端浮点数。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4]);
console.log(buf.readFloatLE(0));
// Prints: 1.539989614439558e-36
console.log(buf.readFloatLE(1));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3, 4]);
console.log(buf.readFloatLE(0));
// Prints: 1.539989614439558e-36
console.log(buf.readFloatLE(1));
// Throws ERR_OUT_OF_RANGE.
buf.readInt8([offset])#
从指定的offset 处的 buf读取有符号的 8 位整数。
从Buffer读取的整数被解释为二进制补码有符号值。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([-1, 5]);
console.log(buf.readInt8(0));
// Prints: -1
console.log(buf.readInt8(1));
// Prints: 5
console.log(buf.readInt8(2));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([-1, 5]);
console.log(buf.readInt8(0));
// Prints: -1
console.log(buf.readInt8(1));
// Prints: 5
console.log(buf.readInt8(2));
// Throws ERR_OUT_OF_RANGE.
buf.readInt16BE([offset])#
从指定的 offset 处的 buf读取有符号的大端 16 位整数。
从Buffer读取的整数被解释为二进制补码有符号值。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 5]);
console.log(buf.readInt16BE(0));
// Prints: 5const { Buffer } = require('node:buffer');
const buf = Buffer.from([0, 5]);
console.log(buf.readInt16BE(0));
// Prints: 5
buf.readInt16LE([offset])#
从指定的 offset 处的 buf读取
有符号的小端 16 位整数。
从Buffer读取的整数被解释为二进制补码有符号值。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 5]);
console.log(buf.readInt16LE(0));
// Prints: 1280
console.log(buf.readInt16LE(1));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([0, 5]);
console.log(buf.readInt16LE(0));
// Prints: 1280
console.log(buf.readInt16LE(1));
// Throws ERR_OUT_OF_RANGE.
buf.readInt32BE([offset])#
从指定的 offset 处的 buf读取有符号的大端 32 位整数。
从Buffer读取的整数被解释为二进制补码有符号值。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 0, 0, 5]);
console.log(buf.readInt32BE(0));
// Prints: 5const { Buffer } = require('node:buffer');
const buf = Buffer.from([0, 0, 0, 5]);
console.log(buf.readInt32BE(0));
// Prints: 5
buf.readInt32LE([offset])#
从指定的 offset 处的 buf读取
有符号的小端 32 位整数。
从Buffer读取的整数被解释为二进制补码有符号值。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 0, 0, 5]);
console.log(buf.readInt32LE(0));
// Prints: 83886080
console.log(buf.readInt32LE(1));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([0, 0, 0, 5]);
console.log(buf.readInt32LE(0));
// Prints: 83886080
console.log(buf.readInt32LE(1));
// Throws ERR_OUT_OF_RANGE.
buf.readIntBE(offset, byteLength)#
offset<整数>开始读取之前要跳过的字节数。必须满足0 <= offset <= buf.length - byteLength。byteLength<整数>要读取的字节数。必须满足0 < byteLength <= 6。- 返回:<整数>
从指定的offset 处的 buf读取byteLength个字节
,并将结果解释为大端、二进制补码有符号值,最多支持 48 位的准确性。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readIntBE(0, 6).toString(16));
// Prints: 1234567890ab
console.log(buf.readIntBE(1, 6).toString(16));
// Throws ERR_OUT_OF_RANGE.
console.log(buf.readIntBE(1, 0).toString(16));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readIntBE(0, 6).toString(16));
// Prints: 1234567890ab
console.log(buf.readIntBE(1, 6).toString(16));
// Throws ERR_OUT_OF_RANGE.
console.log(buf.readIntBE(1, 0).toString(16));
// Throws ERR_OUT_OF_RANGE.
buf.readIntLE(offset, byteLength)#
offset<整数>开始读取之前要跳过的字节数。必须满足0 <= offset <= buf.length - byteLength。byteLength<整数>要读取的字节数。必须满足0 < byteLength <= 6。- 返回:<整数>
从指定的offset 处的 buf读取byteLength 个字节
,并将结果解释为小尾数、支持最多 48 位的二进制补码有符号值的准确性。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readIntLE(0, 6).toString(16));
// Prints: -546f87a9cbeeconst { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readIntLE(0, 6).toString(16));
// Prints: -546f87a9cbee
buf.readUInt8([offset])#
从指定的offset 处的 buf读取无符号 8 位整数。
此函数也可在readUint8别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, -2]);
console.log(buf.readUInt8(0));
// Prints: 1
console.log(buf.readUInt8(1));
// Prints: 254
console.log(buf.readUInt8(2));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, -2]);
console.log(buf.readUInt8(0));
// Prints: 1
console.log(buf.readUInt8(1));
// Prints: 254
console.log(buf.readUInt8(2));
// Throws ERR_OUT_OF_RANGE.
buf.readUInt16BE([offset])#
从指定的offset处的
buf读取无符号、大端 16 位整数。
此函数也可在readUint16BE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56]);
console.log(buf.readUInt16BE(0).toString(16));
// Prints: 1234
console.log(buf.readUInt16BE(1).toString(16));
// Prints: 3456const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56]);
console.log(buf.readUInt16BE(0).toString(16));
// Prints: 1234
console.log(buf.readUInt16BE(1).toString(16));
// Prints: 3456
buf.readUInt16LE([offset])#
从指定的offset处的
buf读取无符号、小端 16 位整数。
此函数也可在readUint16LE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56]);
console.log(buf.readUInt16LE(0).toString(16));
// Prints: 3412
console.log(buf.readUInt16LE(1).toString(16));
// Prints: 5634
console.log(buf.readUInt16LE(2).toString(16));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56]);
console.log(buf.readUInt16LE(0).toString(16));
// Prints: 3412
console.log(buf.readUInt16LE(1).toString(16));
// Prints: 5634
console.log(buf.readUInt16LE(2).toString(16));
// Throws ERR_OUT_OF_RANGE.
buf.readUInt32BE([offset])#
从指定的offset处的
buf读取无符号、大端 32 位整数。
此函数也可在readUint32BE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
console.log(buf.readUInt32BE(0).toString(16));
// Prints: 12345678const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
console.log(buf.readUInt32BE(0).toString(16));
// Prints: 12345678
buf.readUInt32LE([offset])#
从指定的offset处的
buf读取无符号、小端 32 位整数。
此函数也可在readUint32LE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
console.log(buf.readUInt32LE(0).toString(16));
// Prints: 78563412
console.log(buf.readUInt32LE(1).toString(16));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
console.log(buf.readUInt32LE(0).toString(16));
// Prints: 78563412
console.log(buf.readUInt32LE(1).toString(16));
// Throws ERR_OUT_OF_RANGE.
buf.readUIntBE(offset, byteLength)#
offset<整数>开始读取之前要跳过的字节数。必须满足0 <= offset <= buf.length - byteLength。byteLength<整数>要读取的字节数。必须满足0 < byteLength <= 6。- 返回:<整数>
从指定的 offset 处的 buf读取byteLength 个字节
,并将结果解释为支持高达 48 位精度的无符号大端整数。
此函数也可在readUintBE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readUIntBE(0, 6).toString(16));
// Prints: 1234567890ab
console.log(buf.readUIntBE(1, 6).toString(16));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readUIntBE(0, 6).toString(16));
// Prints: 1234567890ab
console.log(buf.readUIntBE(1, 6).toString(16));
// Throws ERR_OUT_OF_RANGE.
buf.readUIntLE(offset, byteLength)#
offset<整数>开始读取之前要跳过的字节数。必须满足0 <= offset <= buf.length - byteLength。byteLength<整数>要读取的字节数。必须满足0 < byteLength <= 6。- 返回:<整数>
从指定offset 处的 buf 读取byteLength 个字节
,并将结果解释为无符号、小端整数,支持高达 48 位精度。
此函数也可在readUintLE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readUIntLE(0, 6).toString(16));
// Prints: ab9078563412const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readUIntLE(0, 6).toString(16));
// Prints: ab9078563412
buf.subarray([start[, end]])#
start<整数>新的Buffer将开始的位置。默认值:0。end<整数>新的Buffer将结束的位置(不包括在内)。 默认值:buf.length。- 返回:<缓冲区>
返回一个新的Buffer,它引用与原始内存相同的内存,但通过start和end索引进行偏移和裁剪。
指定大于{{{ YnVmLmxlbmd0aA==}}}的end 将返回与等于buf.length的end相同的结果。
此方法继承自TypedArray.prototype.subarray()。
修改新的Buffer切片将修改原始Buffer中的内存
,因为两个对象分配的内存重叠。
import { Buffer } from 'node:buffer';
// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
// from the original `Buffer`.
const buf1 = Buffer.allocUnsafe(26);
for (let i = 0; i < 26; i++) {
// 97 is the decimal ASCII value for 'a'.
buf1[i] = i + 97;
}
const buf2 = buf1.subarray(0, 3);
console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: abc
buf1[0] = 33;
console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: !bcconst { Buffer } = require('node:buffer');
// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
// from the original `Buffer`.
const buf1 = Buffer.allocUnsafe(26);
for (let i = 0; i < 26; i++) {
// 97 is the decimal ASCII value for 'a'.
buf1[i] = i + 97;
}
const buf2 = buf1.subarray(0, 3);
console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: abc
buf1[0] = 33;
console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: !bc
指定负索引会导致切片相对于buf的末尾而不是开头生成。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
console.log(buf.subarray(-6, -1).toString());
// Prints: buffe
// (Equivalent to buf.subarray(0, 5).)
console.log(buf.subarray(-6, -2).toString());
// Prints: buff
// (Equivalent to buf.subarray(0, 4).)
console.log(buf.subarray(-5, -2).toString());
// Prints: uff
// (Equivalent to buf.subarray(1, 4).)const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
console.log(buf.subarray(-6, -1).toString());
// Prints: buffe
// (Equivalent to buf.subarray(0, 5).)
console.log(buf.subarray(-6, -2).toString());
// Prints: buff
// (Equivalent to buf.subarray(0, 4).)
console.log(buf.subarray(-5, -2).toString());
// Prints: uff
// (Equivalent to buf.subarray(1, 4).)
buf.slice([start[, end]])#
start<整数>新的Buffer将开始的位置。默认值:0。end<整数>新的Buffer将结束的位置(不包括在内)。 默认值:buf.length。- 返回:<缓冲区>
buf.subarray代替。返回一个新的Buffer,它引用与原始内存相同的内存,但通过start和end索引进行偏移和裁剪。
此方法与Uint8Array.prototype.slice()不兼容,后者是Buffer的超类。要复制切片,请使用
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 的倍数,则抛出{{{RVJSX0lOVkFMSURfQlVGRkVSX1NJWkU =}}} 。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>
buf1.swap16();
console.log(buf1);
// Prints: <Buffer 02 01 04 03 06 05 08 07>
const buf2 = Buffer.from([0x1, 0x2, 0x3]);
buf2.swap16();
// Throws ERR_INVALID_BUFFER_SIZE.const { Buffer } = require('node:buffer');
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>
buf1.swap16();
console.log(buf1);
// Prints: <Buffer 02 01 04 03 06 05 08 07>
const buf2 = Buffer.from([0x1, 0x2, 0x3]);
buf2.swap16();
// Throws ERR_INVALID_BUFFER_SIZE.
buf.swap16()的一种方便用法是在 UTF-16 小端和 UTF-16 大端之间执行快速就地转换:
import { Buffer } from 'node:buffer';
const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
buf.swap16(); // Convert to big-endian UTF-16 text.const { Buffer } = require('node:buffer');
const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
buf.swap16(); // Convert to big-endian UTF-16 text.
buf.swap32()#
- 返回:<Buffer>对
buf的引用。
将buf解释为无符号 32 位整数数组并就地交换字节顺序。如果buf.length
不是 4 的倍数,则抛出{{{RVJSX0lOVkFMSURfQlVGRkVSX1NJWkU =}}} 。
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 的倍数,则抛出{{{RVJSX0lOVkFMSURfQlVGRkVSX1NJWkU =}}} 。
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()#
- 返回:<对象>
返回buf的 JSON 表示形式。当字符串化Buffer实例时, JSON.stringify()隐式调用此函数。
Buffer.from()接受从此方法返回的格式的对象。特别是,Buffer.from(buf.toJSON())的工作方式类似于Buffer.from(buf)。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
const json = JSON.stringify(buf);
console.log(json);
// Prints: {"type":"Buffer","data":[1,2,3,4,5]}
const copy = JSON.parse(json, (key, value) => {
return value && value.type === 'Buffer' ?
Buffer.from(value) :
value;
});
console.log(copy);
// Prints: <Buffer 01 02 03 04 05>const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
const json = JSON.stringify(buf);
console.log(json);
// Prints: {"type":"Buffer","data":[1,2,3,4,5]}
const copy = JSON.parse(json, (key, value) => {
return value && value.type === 'Buffer' ?
Buffer.from(value) :
value;
});
console.log(copy);
// Prints: <Buffer 01 02 03 04 05>
buf.toString([encoding[, start[, end]]])#
encoding<string>要使用的字符编码。默认值:'utf8'。start<integer>开始解码的字节偏移量。默认值:0。end<integer>停止解码的字节偏移量(不包括在内)。 默认值:buf.length。- 返回:<字符串>
根据
encoding 中指定的字符编码将 buf解码为字符串。可以传递start和end来仅解码buf的子集。
如果encoding为'utf8'并且输入中的字节序列不是有效的 UTF-8,则每个无效字节将替换为替换字符U+FFFD。
字符串实例的最大长度(以 UTF-16 代码单元表示)可用作buffer.constants.MAX_STRING_LENGTH。
import { Buffer } from 'node:buffer';
const buf1 = Buffer.allocUnsafe(26);
for (let i = 0; i < 26; i++) {
// 97 is the decimal ASCII value for 'a'.
buf1[i] = i + 97;
}
console.log(buf1.toString('utf8'));
// Prints: abcdefghijklmnopqrstuvwxyz
console.log(buf1.toString('utf8', 0, 5));
// Prints: abcde
const buf2 = Buffer.from('tést');
console.log(buf2.toString('hex'));
// Prints: 74c3a97374
console.log(buf2.toString('utf8', 0, 3));
// Prints: té
console.log(buf2.toString(undefined, 0, 3));
// Prints: téconst { Buffer } = require('node:buffer');
const buf1 = Buffer.allocUnsafe(26);
for (let i = 0; i < 26; i++) {
// 97 is the decimal ASCII value for 'a'.
buf1[i] = i + 97;
}
console.log(buf1.toString('utf8'));
// Prints: abcdefghijklmnopqrstuvwxyz
console.log(buf1.toString('utf8', 0, 5));
// Prints: abcde
const buf2 = Buffer.from('tést');
console.log(buf2.toString('hex'));
// Prints: 74c3a97374
console.log(buf2.toString('utf8', 0, 3));
// Prints: té
console.log(buf2.toString(undefined, 0, 3));
// Prints: té
buf.values()#
- 返回:<迭代器>
创建并返回buf值(字节)的迭代器。当在for..of语句中使用Buffer时,会自动调用此函数。
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
for (const value of buf.values()) {
console.log(value);
}
// Prints:
// 98
// 117
// 102
// 102
// 101
// 114
for (const value of buf) {
console.log(value);
}
// Prints:
// 98
// 117
// 102
// 102
// 101
// 114const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
for (const value of buf.values()) {
console.log(value);
}
// Prints:
// 98
// 117
// 102
// 102
// 101
// 114
for (const value of buf) {
console.log(value);
}
// Prints:
// 98
// 117
// 102
// 102
// 101
// 114
buf.write(string[, offset[, length]][, encoding])#
string<string>要写入buf的字符串。offset<integer>开始写入string之前要跳过的字节数。 默认值:0。length<integer>要写入的最大字节数(写入的字节数不会超过buf.length - offset)。默认值:buf.length - offset。encoding<string>string的字符编码。默认值:'utf8'。- 返回:<整数>写入的字节数。
根据
{{{ ZW5jb2Rpbmc= }}} 中的字符编码将string写入offset处的 buf 。length参数是要写入的字节数。如果buf没有足够的空间来容纳整个字符串,则仅写入string的一部分。但是,不会写入部分编码的字符。
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(256);
const len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
// Prints: 12 bytes: ½ + ¼ = ¾
const buffer = Buffer.alloc(10);
const length = buffer.write('abcd', 8);
console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
// Prints: 2 bytes : abconst { Buffer } = require('node:buffer');
const buf = Buffer.alloc(256);
const len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
// Prints: 12 bytes: ½ + ¼ = ¾
const buffer = Buffer.alloc(10);
const length = buffer.write('abcd', 8);
console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
// Prints: 2 bytes : ab
buf.writeBigInt64BE(value[, offset])#
value<bigint>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足:0 <= offset <= buf.length - 8。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以大尾数法写入指定的offset处的buf。
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<整数>开始写入之前要跳过的字节数。必须满足:0 <= offset <= buf.length - 8。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以小端方式写入指定的offset处的 buf。
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<整数>开始写入之前要跳过的字节数。必须满足:0 <= offset <= buf.length - 8。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以大尾数法写入指定的offset处的buf。
此函数也可在writeBigUint64BE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
console.log(buf);
// Prints: <Buffer de ca fa fe ca ce fa de>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
console.log(buf);
// Prints: <Buffer de ca fa fe ca ce fa de>
buf.writeBigUInt64LE(value[, offset])#
value<bigint>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足:0 <= offset <= buf.length - 8。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以小端方式写入指定的offset处的 buf
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
console.log(buf);
// Prints: <Buffer de fa ce ca fe fa ca de>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
console.log(buf);
// Prints: <Buffer de fa ce ca fe fa ca de>
此函数也可在writeBigUint64LE别名下使用。
buf.writeDoubleBE(value[, offset])#
value<number>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足0 <= offset <= buf.length - 8。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以大尾数法写入指定的offset处的buf。value
必须是 JavaScript 数字。当value不是 JavaScript 数字时,行为未定义。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
buf.writeDoubleBE(123.456, 0);
console.log(buf);
// Prints: <Buffer 40 5e dd 2f 1a 9f be 77>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
buf.writeDoubleBE(123.456, 0);
console.log(buf);
// Prints: <Buffer 40 5e dd 2f 1a 9f be 77>
buf.writeDoubleLE(value[, offset])#
value<number>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足0 <= offset <= buf.length - 8。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以小端方式写入指定的offset处的 buf。value必须是 JavaScript编号
。当value不是 JavaScript 数字时,行为未定义。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
buf.writeDoubleLE(123.456, 0);
console.log(buf);
// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
buf.writeDoubleLE(123.456, 0);
console.log(buf);
// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>
buf.writeFloatBE(value[, offset])#
value<number>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足0 <= offset <= buf.length - 4。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以大尾数法写入指定的offset处的buf。当value不是 JavaScript 数字时,行为未定义。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeFloatBE(0xcafebabe, 0);
console.log(buf);
// Prints: <Buffer 4f 4a fe bb>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeFloatBE(0xcafebabe, 0);
console.log(buf);
// Prints: <Buffer 4f 4a fe bb>
buf.writeFloatLE(value[, offset])#
value<number>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足0 <= offset <= buf.length - 4。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以小端方式写入指定的offset处的 buf。当value不是 JavaScript 数字时,行为未定义。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeFloatLE(0xcafebabe, 0);
console.log(buf);
// Prints: <Buffer bb fe 4a 4f>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeFloatLE(0xcafebabe, 0);
console.log(buf);
// Prints: <Buffer bb fe 4a 4f>
buf.writeInt8(value[, offset])#
value<integer>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足0 <= offset <= buf.length - 1。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value写入指定的offset 处的 buf。value必须是有效的有符号 8 位整数。当value不是带符号的 8 位整数时,行为未定义。
value被解释并写入为二进制补码有符号整数。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
buf.writeInt8(2, 0);
buf.writeInt8(-2, 1);
console.log(buf);
// Prints: <Buffer 02 fe>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
buf.writeInt8(2, 0);
buf.writeInt8(-2, 1);
console.log(buf);
// Prints: <Buffer 02 fe>
buf.writeInt16BE(value[, offset])#
value<integer>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足{{{MCA8PSBvZmZzZXQgPD0gYnVmLmxlbmd0aCAtIDI=}}}。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以大尾数法写入指定的offset处的buf。value
必须是有效的有符号 16 位整数。当value不是有符号 16 位整数时,行为未定义。
value被解释并写入为二进制补码有符号整数。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
buf.writeInt16BE(0x0102, 0);
console.log(buf);
// Prints: <Buffer 01 02>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
buf.writeInt16BE(0x0102, 0);
console.log(buf);
// Prints: <Buffer 01 02>
buf.writeInt16LE(value[, offset])#
value<integer>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足{{{MCA8PSBvZmZzZXQgPD0gYnVmLmxlbmd0aCAtIDI=}}}。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以小端方式写入指定的offset处的 buf。value
必须是有效的有符号 16 位整数。当value不是有符号 16 位整数时,行为未定义。
value被解释并写入为二进制补码有符号整数。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
buf.writeInt16LE(0x0304, 0);
console.log(buf);
// Prints: <Buffer 04 03>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
buf.writeInt16LE(0x0304, 0);
console.log(buf);
// Prints: <Buffer 04 03>
buf.writeInt32BE(value[, offset])#
value<integer>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足0 <= offset <= buf.length - 4。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以大尾数法写入指定的offset处的buf。value
必须是有效的有符号 32 位整数。当value不是带符号的 32 位整数时,行为未定义。
value被解释并写入为二进制补码有符号整数。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeInt32BE(0x01020304, 0);
console.log(buf);
// Prints: <Buffer 01 02 03 04>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeInt32BE(0x01020304, 0);
console.log(buf);
// Prints: <Buffer 01 02 03 04>
buf.writeInt32LE(value[, offset])#
value<integer>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足0 <= offset <= buf.length - 4。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以小端方式写入指定的offset处的 buf。value
必须是有效的有符号 32 位整数。当value不是带符号的 32 位整数时,行为未定义。
value被解释并写入为二进制补码有符号整数。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeInt32LE(0x05060708, 0);
console.log(buf);
// Prints: <Buffer 08 07 06 05>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeInt32LE(0x05060708, 0);
console.log(buf);
// Prints: <Buffer 08 07 06 05>
buf.writeIntBE(value, offset, byteLength)#
value<integer>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足0 <= offset <= buf.length - byteLength。byteLength<整数>要写入的字节数。必须满足0 < byteLength <= 6。- 返回:<integer>
offset加上写入的字节数。
将value的byteLength个字节以
大端方式写入指定的offset处的 buf。支持高达 48 位的精度。当value不是有符号整数时,行为未定义
。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
buf.writeIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer 12 34 56 78 90 ab>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
buf.writeIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer 12 34 56 78 90 ab>
buf.writeIntLE(value, offset, byteLength)#
value<integer>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足0 <= offset <= buf.length - byteLength。byteLength<整数>要写入的字节数。必须满足0 < byteLength <= 6。- 返回:<integer>
offset加上写入的字节数。
将value的byteLength个字节以
小端方式写入指定的offset处的 buf。支持高达 48 位的精度。当value不是有符号整数时,行为未定义。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
buf.writeIntLE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer ab 90 78 56 34 12>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
buf.writeIntLE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer ab 90 78 56 34 12>
buf.writeUInt8(value[, offset])#
value<integer>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足0 <= offset <= buf.length - 1。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value写入指定的offset 处的 buf。value必须是有效的无符号 8 位整数。当value不是无符号 8 位整数时,行为未定义。
此函数也可在writeUint8别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeUInt8(0x3, 0);
buf.writeUInt8(0x4, 1);
buf.writeUInt8(0x23, 2);
buf.writeUInt8(0x42, 3);
console.log(buf);
// Prints: <Buffer 03 04 23 42>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeUInt8(0x3, 0);
buf.writeUInt8(0x4, 1);
buf.writeUInt8(0x23, 2);
buf.writeUInt8(0x42, 3);
console.log(buf);
// Prints: <Buffer 03 04 23 42>
buf.writeUInt16BE(value[, offset])#
value<integer>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足{{{MCA8PSBvZmZzZXQgPD0gYnVmLmxlbmd0aCAtIDI=}}}。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以大尾数法写入指定的offset处的buf。value
必须是有效的无符号 16 位整数。当value
不是无符号 16 位整数时,行为未定义。
此函数也可在writeUint16BE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeUInt16BE(0xdead, 0);
buf.writeUInt16BE(0xbeef, 2);
console.log(buf);
// Prints: <Buffer de ad be ef>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeUInt16BE(0xdead, 0);
buf.writeUInt16BE(0xbeef, 2);
console.log(buf);
// Prints: <Buffer de ad be ef>
buf.writeUInt16LE(value[, offset])#
value<integer>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足{{{MCA8PSBvZmZzZXQgPD0gYnVmLmxlbmd0aCAtIDI=}}}。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以小端方式写入指定的offset处的 buf。value
必须是有效的无符号 16 位整数。当value不是无符号 16 位整数时,行为未定义。
此函数也可在writeUint16LE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeUInt16LE(0xdead, 0);
buf.writeUInt16LE(0xbeef, 2);
console.log(buf);
// Prints: <Buffer ad de ef be>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeUInt16LE(0xdead, 0);
buf.writeUInt16LE(0xbeef, 2);
console.log(buf);
// Prints: <Buffer ad de ef be>
buf.writeUInt32BE(value[, offset])#
value<integer>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足0 <= offset <= buf.length - 4。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以大尾数法写入指定的offset处的buf。value
必须是有效的无符号 32 位整数。当value
不是无符号 32 位整数时,行为未定义。
此函数也可在writeUint32BE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeUInt32BE(0xfeedface, 0);
console.log(buf);
// Prints: <Buffer fe ed fa ce>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeUInt32BE(0xfeedface, 0);
console.log(buf);
// Prints: <Buffer fe ed fa ce>
buf.writeUInt32LE(value[, offset])#
value<integer>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足0 <= offset <= buf.length - 4。默认值:0。- 返回:<integer>
offset加上写入的字节数。
将value以小端方式写入指定的offset处的 buf。value
必须是有效的无符号 32 位整数。当value不是无符号 32 位整数时,行为未定义。
此函数也可在writeUint32LE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
buf.writeUInt32LE(0xfeedface, 0);
console.log(buf);
// Prints: <Buffer ce fa ed fe>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
buf.writeUInt32LE(0xfeedface, 0);
console.log(buf);
// Prints: <Buffer ce fa ed fe>
buf.writeUIntBE(value, offset, byteLength)#
value<integer>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足0 <= offset <= buf.length - byteLength。byteLength<整数>要写入的字节数。必须满足0 < byteLength <= 6。- 返回:<integer>
offset加上写入的字节数。
将value的byteLength个字节以
大端方式写入指定的offset处的 buf。支持高达 48 位的精度。当value不是无符号整数时,行为未定义。
此函数也可在writeUintBE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
buf.writeUIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer 12 34 56 78 90 ab>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
buf.writeUIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer 12 34 56 78 90 ab>
buf.writeUIntLE(value, offset, byteLength)#
value<integer>要写入buf的数字。offset<整数>开始写入之前要跳过的字节数。必须满足0 <= offset <= buf.length - byteLength。byteLength<整数>要写入的字节数。必须满足0 < byteLength <= 6。- 返回:<integer>
offset加上写入的字节数。
将value的byteLength个字节以
小端方式写入指定的offset处的 buf。支持高达 48 位的精度。当value不是无符号整数时,行为未定义。
此函数也可在writeUintLE别名下使用。
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
buf.writeUIntLE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer ab 90 78 56 34 12>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
buf.writeUIntLE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer ab 90 78 56 34 12>
new Buffer(array)#
Buffer.from(array)代替。array<integer[]>要复制的字节数组。
new Buffer(arrayBuffer[, byteOffset[, length]])#
Buffer.from(arrayBuffer[, byteOffset[, length]])
代替。arrayBuffer<ArrayBuffer> | <SharedArrayBuffer> { {{QXJyYXlCdWZmZmZXI=}}}、SharedArrayBuffer或TypedArray的{{{LmJ1ZmZlcg==}} }属性。byteOffset<integer>要公开的第一个字节的索引。默认值:0。length<integer>要公开的字节数。 默认值:arrayBuffer.byteLength - byteOffset。
请参阅
Buffer.from(arrayBuffer[, byteOffset[, length]])。
new Buffer(buffer)#
Buffer.from(buffer)代替。buffer<缓冲区> | <Uint8Array>要从中复制数据的现有Buffer或Uint8Array。
new Buffer(size)#
size<integer>新的Buffer的所需长度。
请参阅Buffer.alloc()和Buffer.allocUnsafe()。构造函数的此变体相当于Buffer.alloc()。
new Buffer(string[, encoding])#
Buffer.from(string[, encoding])代替。类:File#
- 扩展:<Blob>
File提供有关文件的信息。
new buffer.File(sources, fileName[, options])#
sources<字符串[]> | <数组缓冲区[]> | <TypedArray[]> | <数据视图[]> | <斑点[]> | <File[]> 字符串数组、<ArrayBuffer>、<TypedArray>、<DataView>、<File>或<Blob> 对象或此类对象的任意组合,将存储在File。fileName<string>文件的名称。options<对象>
file.name#
- 类型:<字符串>
File的名称。
file.lastModified#
- 类型:<数字>
File的最后修改日期。
node:buffer模块 API#
虽然Buffer对象可作为全局对象使用,但还有其他与
Buffer相关的 API,这些 API 只能通过使用node:buffer模块访问cmVxdWlyZSgnbm9kZTpidWZmZXInKQ==}}}。
buffer.atob(data)#
Buffer.from(data, 'base64')。data<any> Base64 编码的输入字符串。
将 Base64 编码数据字符串解码为字节,并使用 Latin-1 (ISO-8859-1) 将这些字节编码为字符串。
data可以是任何可以强制转换为字符串的 JavaScript 值。
提供此函数只是为了与旧版 Web 平台 API 兼容,并且永远不应在新代码中使用,因为它们使用字符串来表示二进制数据,并且早于 JavaScript 中类型化数组的引入。对于使用 Node.js API 运行的代码,应使用Buffer.from(str, 'base64')和
buf.toString('base64')执行 Base64 编码字符串和二进制数据之间的转换。
buffer.btoa(data)#
buf.toString('base64')。data<any> ASCII (Latin1) 字符串。
使用 Latin-1 (ISO-8859) 将字符串解码为字节,并使用 Base64 将这些字节编码为字符串。
data可以是任何可以强制转换为字符串的 JavaScript 值。
提供此函数只是为了与旧版 Web 平台 API 兼容,并且永远不应在新代码中使用,因为它们使用字符串来表示二进制数据,并且早于 JavaScript 中类型化数组的引入。对于使用 Node.js API 运行的代码,应使用Buffer.from(str, 'base64')和
buf.toString('base64')执行 Base64 编码字符串和二进制数据之间的转换。
buffer.isAscii(input)#
- 输入<缓冲区> | <数组缓冲区> | <TypedArray>要验证的输入。
- 返回:<布尔值>
如果input仅包含有效的 ASCII 编码数据(包括 input为空的情况),则此函数返回 true 。
如果input是分离的数组缓冲区,则抛出此错误。
buffer.isUtf8(input)#
- 输入<缓冲区> | <数组缓冲区> | <TypedArray>要验证的输入。
- 返回:<布尔值>
如果input仅包含有效的 UTF-8 编码数据(包括 input为空的情况),则此函数返回 true 。
如果input是分离的数组缓冲区,则抛出此错误。
buffer.INSPECT_MAX_BYTES#
- <整数> 默认值:
50
返回调用buf.inspect()时将返回的最大字节数
。这可以被用户模块覆盖。有关buf.inspect()行为的更多详细信息,请参阅
util.inspect() 。
buffer.kMaxLength#
- <integer>单个
Buffer实例允许的最大大小。
buffer.constants.MAX_LENGTH的别名。
buffer.kStringMaxLength#
- <integer>单个
string实例允许的最大长度。
buffer.constants.MAX_STRING_LENGTH的别名。
buffer.resolveObjectURL(id)#
解析'blob:nodedata:...'一个关联的<Blob>对象,该对象是使用先前调用URL.createObjectURL()注册的。
buffer.transcode(source, fromEnc, toEnc)#
source<缓冲区> | <Uint8Array>一个Buffer或Uint8Array实例。fromEnc<string>当前编码。- {{{dG9FbmM=}}} <string>目标编码。
- 返回:<缓冲区>
将给定的Buffer或Uint8Array实例从一种字符编码重新编码为另一种字符编码。返回一个新的Buffer实例。
如果fromEnc或{{{dG9FbmM=}}}指定无效的字符编码或不允许从fromEnc到{{{dG9FbmM=}}} 的转换,则抛出此错误。
buffer.transcode()支持的编码有:'ascii'、'utf8'、
'utf16le'、'ucs2'、'latin1'和'binary'。
如果给定的字节序列无法在目标编码中充分表示,则转码过程将使用替换字符。例如:
import { Buffer, transcode } from 'node:buffer';
const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
console.log(newBuf.toString('ascii'));
// Prints: '?'const { Buffer, transcode } = require('node:buffer');
const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
console.log(newBuf.toString('ascii'));
// Prints: '?'
由于欧元 ( b, ) 符号无法用 US-ASCII 表示,因此在转码后的Buffer 中它被替换为 ?。
类别:SlowBuffer#
Buffer.allocUnsafeSlow()代替。请参阅Buffer.allocUnsafeSlow()。从构造函数总是返回Buffer实例,而不是SlowBuffer
实例的意义上来说,这从来都不是一个类。
new SlowBuffer(size)#
Buffer.allocUnsafeSlow()代替。size<integer>新的SlowBuffer的所需长度。
缓冲区常数#
buffer.constants.MAX_LENGTH#
- <integer>单个
Buffer实例允许的最大大小。
在 32 位架构上,该值当前为 2 30 - 1(大约 1 GiB)。
在 64 位架构上,该值当前为 2 32(约 4 GiB)。
它在引擎盖下反映了v8::TypedArray::kMaxLength 。
此值也可用作buffer.kMaxLength。
buffer.constants.MAX_STRING_LENGTH#
- <integer>单个
string实例允许的最大长度。
表示string原语可以拥有的最大length,以 UTF-16 代码单元计数。
该值可能取决于正在使用的 JS 引擎。
Buffer.from()、Buffer.alloc()和Buffer.allocUnsafe()#
在 6.0.0 之前的 Node.js 版本中,Buffer实例是使用Buffer构造函数创建的
,该函数
根据参数不同地分配返回的Buffer提供:
- 将数字作为第一个参数传递给
Buffer()(例如new Buffer(10))会分配指定大小的新Buffer对象。在 Node.js 8.0.0 之前,为此类Buffer实例分配的内存未初始化,并且 可能包含敏感数据。随后必须使用{{ { YnVmLmZpbGwoMCk=}}}或通过写入整个Buffer实例来初始化此类Buffer实例,然后再从Buffer读取数据。虽然此行为是为了提高性能,但开发经验表明,创建快速但未初始化的Buffer与创建较慢但更安全的Buffer之间需要更明确的区别。从 Node.js 8.0.0 开始,Buffer(num)和new Buffer(num)返回带有初始化内存的Buffer。 - 传递字符串、数组或
Buffer作为第一个参数会将传递的对象的数据复制到Buffer中。 - 传递
ArrayBuffer或SharedArrayBuffer返回 与给定数组缓冲区共享分配内存的Buffer。
由于new Buffer()的行为根据第一个参数的类型而有所不同,因此当未执行参数验证或Buffer初始化时,可能会无意中将安全性和可靠性问题引入应用程序。
例如,如果攻击者可以使应用程序在需要字符串的情况下接收数字,则应用程序可能会调用 new Buffer(100)
而不是new Buffer("100"),从而导致它分配 100 字节的缓冲区而不是分配一个包含内容"100"的 3 字节缓冲区。这通常可以使用 JSON API 调用来实现。由于 JSON 区分数字和字符串类型,因此它允许在未充分验证其输入的天真编写的应用程序可能期望始终接收字符串的情况下注入数字。在 Node.js 8.0.0 之前,100 字节缓冲区可能包含任意预先存在的内存中数据,因此可用于向远程攻击者公开内存中的秘密。从 Node.js 8.0.0 开始,不会发生内存泄露,因为数据是零填充的。然而,其他攻击仍然是可能的,例如导致服务器分配非常大的缓冲区,导致性能下降或内存耗尽时崩溃。
为了使Buffer实例的创建更加可靠且不易出错,各种形式的new Buffer()构造函数已被弃用
,并替换为单独的Buffer.from()、Buffer.alloc()和
Buffer.allocUnsafe()方法。
开发人员应将new Buffer()构造函数的所有现有用途迁移到这些新 API 之一。
Buffer.from(array)返回一个新的Buffer,其中所提供的八位字节的副本。Buffer.from(arrayBuffer[, byteOffset[, length]])返回一个新的Buffer,它与给定的ArrayBuffer共享相同的分配内存。Buffer.from(buffer)返回一个新的Buffer,其中包含给定Buffer内容的副本。Buffer.from(string[, encoding])返回一个新的Buffer,其中所提供字符串的副本。Buffer.alloc(size[, fill[, encoding]])返回指定大小的新初始化的Buffer。此方法比Buffer.allocUnsafe(size)慢 ,但保证新创建的Buffer实例永远不会包含潜在敏感的旧数据。如果size不是数字,则会抛出TypeError。Buffer.allocUnsafe(size)和Buffer.allocUnsafeSlow(size)各自返回指定的size的新的未初始化的Buffer。由于Buffer未初始化,分配的内存段可能包含潜在敏感的旧数据。
如果size小于或等于,则Buffer.allocUnsafe()和
Buffer.from(array) 返回的 Buffer 实例可以从共享内部内存池中分配到一半Buffer.poolSize。Buffer.allocUnsafeSlow()返回的实例从不使用共享内部内存池。
--zero-fill-buffers命令行选项#
Node.js 可以使用--zero-fill-buffers命令行选项启动,以使所有新分配的Buffer实例在创建时默认为零填充。如果没有该选项,则使用Buffer.allocUnsafe()、
Buffer.allocUnsafeSlow()和new SlowBuffer(size)创建的缓冲区不会填充零。使用此标志可能会对性能产生明显的负面影响。仅当需要强制新分配的
Buffer实例不能包含可能敏感的旧数据时,才使用
--zero-fill-buffers选项。
$ node --zero-fill-buffers
> Buffer.allocUnsafe(5);
<Buffer 00 00 00 00 00>
是什么让Buffer.allocUnsafe()和Buffer.allocUnsafeSlow() “不安全”?#
当调用Buffer.allocUnsafe()和Buffer.allocUnsafeSlow()时,分配的内存段未初始化(未清零)。虽然这种设计使内存分配速度相当快,但分配的内存段可能包含潜在敏感的旧数据。使用
由{{{QnVmZmVyLmFsbG9jVW5zYWZlKCk =}}} 创建的 Buffer而不完全覆盖内存可能会导致在读取Buffer内存时泄漏旧数据。
虽然使用
Buffer.allocUnsafe()有明显的性能优势,但必须格外小心,以避免将安全漏洞引入应用程序。