📜  Node.js 中的缓冲区是什么?

📅  最后修改于: 2022-05-13 01:56:30.914000             🧑  作者: Mango

Node.js 中的缓冲区是什么?

纯 JavaScript 非常适合 Unicode 编码的字符串,但它不能很好地处理二进制数据。当我们在浏览器级别对数据进行操作时没有问题,但在处理 TCP 流和对文件系统执行读写操作时需要处理纯二进制数据。为了满足这个需求,Node.js 使用了 Buffer,所以在本文中,我们将了解 Node.js 中的缓冲区。

Node.js 中的缓冲区:Node.js中的 Buffer 类用于对原始二进制数据执行操作。通常,Buffer 是指内存中的特定内存位置。缓冲区和数组有一些相似之处,但不同的是数组可以是任意类型,并且可以调整大小。缓冲区只处理二进制数据,不能调整大小。缓冲区中的每个整数代表一个字节。 console.log()函数用于打印 Buffer 实例。

对 Buffer执行操作的方法

NoMethodDescription
1Buffer.alloc(size)It creates a buffer and allocates size to it.
2Buffer.from(initialization)It initializes the buffer with given data.
3Buffer.write(data)It writes the data on the buffer.
4toString()It read data from the buffer and returned it.
5Buffer.isBuffer(object)It checks whether the object is a buffer or not.
6Buffer.lengthIt returns the length of the buffer.
7Buffer.copy(buffer,subsection size)It copies data from one buffer to another.
8Buffer.slice(start, end=buffer.length)It returns the subsection of data stored in a buffer.
9Buffer.concat([buffer,buffer])It concatenates two buffers.

文件名:index.js

Javascript
// Different Method to create Buffer
var buffer1 = Buffer.alloc(100);
var buffer2 = new Buffer('GFG');
var buffer3 = Buffer.from([1, 2, 3, 4]);
 
// Writing data to Buffer
buffer1.write("Happy Learning");
 
// Reading data from Buffer
var a = buffer1.toString('utf-8');
console.log(a);
 
// Check object is buffer or not
console.log(Buffer.isBuffer(buffer1));
 
// Check length of Buffer
console.log(buffer1.length);
 
// Copy buffer
var bufferSrc = new Buffer('ABC');
var bufferDest = Buffer.alloc(3);
bufferSrc.copy(bufferDest);
 
var Data = bufferDest.toString('utf-8');
console.log(Data);
 
// Slicing data
var bufferOld = new Buffer('GeeksForGeeks');
var bufferNew = bufferOld.slice(0, 4);
console.log(bufferNew.toString());
 
// concatenate two buffer
var bufferOne = new Buffer('Happy Learning ');
var bufferTwo = new Buffer('With GFG');
var bufferThree = Buffer.concat([bufferOne, bufferTwo]);
console.log(bufferThree.toString());


使用以下命令运行index.js文件:

node index.js

输出:

Happy Learning
true
100
ABC
Geek
Happy Learning With GFG

参考: https://nodejs.org/api/buffer.html