PHP前端开发

缓冲区:Nodejs

百变鹏仔 3天前 #JavaScript
文章标签 缓冲区

node.js 中缓冲区的简单指南

node.js 中的 buffer 用于处理原始二进制数据,这在处理流、文件或网络数据时非常有用。

如何创建缓冲区

  1. 来自字符串
   const buf = buffer.from('hello');
  1. 分配特定大小的缓冲区:
   const buf = buffer.alloc(10); // 10-byte buffer filled with zeros
  1. 来自字节数组:
   const buf = buffer.from([72, 101, 108, 108, 111]); // represents 'hello'

重要的缓冲区功能

  1. 将缓冲区转换为字符串:
   const buf = buffer.from('hello');   console.log(buf.tostring()); // 'hello'
  1. 获取缓冲区长度:
   const buf = buffer.from('hello');   console.log(buf.length); // 5 (each character takes 1 byte)
  1. 将数据写入缓冲区:
   const buf = buffer.alloc(5);   buf.write('hi');   console.log(buf.tostring()); // 'hi'
  1. 对缓冲区进行切片:
   const buf = buffer.from('hello world');   const slice = buf.slice(0, 5);   console.log(slice.tostring()); // 'hello'
  1. 从一个缓冲区复制到另一个缓冲区:
   const buf1 = buffer.from('hello');   const buf2 = buffer.alloc(5);   buf1.copy(buf2);   console.log(buf2.tostring()); // 'hello'
  1. 比较两个缓冲区:
   const buf1 = buffer.from('abc');   const buf2 = buffer.from('abc');   console.log(buf1.equals(buf2)); // true
  1. 连接多个缓冲区:
   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 中的大多数初学者用例!