
node.js 中缓冲区的简单指南
node.js 中的 buffer 用于处理原始二进制数据,这在处理流、文件或网络数据时非常有用。
如何创建缓冲区
- 来自字符串:
const buf = buffer.from('hello');
- 分配特定大小的缓冲区:
const buf = buffer.alloc(10); // 10-byte buffer filled with zeros
- 来自字节数组:
const buf = buffer.from([72, 101, 108, 108, 111]); // represents 'hello'
重要的缓冲区功能
- 将缓冲区转换为字符串:
const buf = buffer.from('hello');
console.log(buf.tostring()); // 'hello'
- 获取缓冲区长度:
const buf = buffer.from('hello');
console.log(buf.length); // 5 (each character takes 1 byte)
- 将数据写入缓冲区:
const buf = buffer.alloc(5);
buf.write('hi');
console.log(buf.tostring()); // 'hi'
- 对缓冲区进行切片:
const buf = buffer.from('hello world');
const slice = buf.slice(0, 5);
console.log(slice.tostring()); // 'hello'
- 从一个缓冲区复制到另一个缓冲区:
const buf1 = buffer.from('hello');
const buf2 = buffer.alloc(5);
buf1.copy(buf2);
console.log(buf2.tostring()); // 'hello'
- 比较两个缓冲区:
const buf1 = buffer.from('abc');
const buf2 = buffer.from('abc');
console.log(buf1.equals(buf2)); // true
- 连接多个缓冲区:
const buf1 = Buffer.from('Hello');
const buf2 = Buffer.from(' World');
const buf3 = Buffer.concat([buf1, buf2]);
console.log(buf3.toString()); // 'Hello World'
这些是开始在 node.js 中处理二进制数据时需要了解的关键 buffer 函数:
内容:生产级 Node.js 后端模式,涵盖 Express/Fastify 配置、分层架构、中间件、错误处理、验证、数据库集成、身份验证及缓存。 时机:构建 REST API、搭建 Node.js 服务器、实施身份验证、集成数据库、添加验证/缓存或构建后端应用结构时。 关键词:nodejs, node, express, fastify, typescript, api, rest, 中间件, 身份验证, jwt, 验证, zod, postgres, mongodb, redis, 缓存, 速率限
- 创建、写入和读取缓冲区
- 切片、复制、比较和连接缓冲区
这足以处理 node.js 中的大多数初学者用例!

















