// 创建一个 Buffer 实例,长度为 10
const buf1 = Buffer.alloc(10);
console.log(buf1); // 输出: <Buffer 00 00 00 00 00 00 00 00 00 00>
// 创建一个包含特定内容的 Buffer 实例
const buf2 = Buffer.from('Hello, world!', 'utf8');
console.log(buf2); // 输出: <Buffer 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21>
// 将 Buffer 转换为字符串
const str = buf2.toString('utf8');
console.log(str); // 输出: Hello, world!
// 修改 Buffer 中的内容
buf2[0] = 72; // 将第一个字节修改为 ASCII 码 72 (即大写的 H)
console.log(buf2.toString('utf8')); // 输出: Hello, world!
// 将 Buffer 转换为 JSON 对象
const json = buf2.toJSON();
console.log(json);
// 输出: { type: 'Buffer', data: [ 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33 ] }
// 拷贝 Buffer 内容到另一个 Buffer
const buf3 = Buffer.alloc(16);
buf2.copy(buf3);
console.log(buf3.toString('utf8')); // 输出: Hello, world!
Buffer.alloc(size):创建一个指定大小的 Buffer 实例,并初始化为零。Buffer.from(string[, encoding]):根据给定的字符串和编码创建一个 Buffer 实例。toString([encoding]):将 Buffer 转换为字符串,指定编码格式(如 UTF-8)。buffer[index]:直接访问 Buffer 中的某个字节并进行修改。toJSON():将 Buffer 转换为 JSON 对象,方便序列化。copy(targetBuffer[, targetStart[, sourceStart[, sourceEnd]]]):将当前 Buffer 的内容拷贝到另一个 Buffer 中。上一篇:js const用法
下一篇:js 深拷贝方法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站