What is buffer in Node.js ?
Last Updated :
03 Apr, 2023
Pure JavaScript is great with Unicode-encoded strings, but it does not handle binary data very well. It is not problematic when we perform an operation on data at the browser level but at the time of dealing with TCP stream and performing a read-write operation on the file system is required to deal with pure binary data. To satisfy this need Node.js use Buffer, So in this article, we are going to know about buffer in Node.js.
Buffers in Node.js: The Buffer class in Node.js is used to perform operations on raw binary data. Generally, Buffer refers to the particular memory location in memory. Buffer and array have some similarities, but the difference is array can be any type, and it can be resizable. Buffers only deal with binary data, and it can not be resizable. Each integer in a buffer represents a byte. console.log() function is used to print the Buffer instance.
Methods to perform the operations on Buffer:
No |
Method |
Description |
1 |
Buffer.alloc(size) |
It creates a buffer and allocates size to it. |
2 |
Buffer.from(initialization) |
It initializes the buffer with given data. |
3 |
Buffer.write(data) |
It writes the data on the buffer. |
4 |
toString() |
It read data from the buffer and returned it. |
5 |
Buffer.isBuffer(object) |
It checks whether the object is a buffer or not. |
6 |
Buffer.length |
It returns the length of the buffer. |
7 |
Buffer.copy(buffer,subsection size) |
It copies data from one buffer to another. |
8 |
Buffer.slice(start, end=buffer.length) |
It returns the subsection of data stored in a buffer. |
9 |
Buffer.concat([buffer,buffer]) |
It concatenates two buffers. |
Filename: index.js
Javascript
const buffer1 = Buffer.alloc(100);
const buffer2 = new Buffer( 'GFG' );
const buffer3 = Buffer.from([1, 2, 3, 4]);
buffer1.write( "Happy Learning" );
const a = buffer1.toString( 'utf-8' );
console.log(a);
console.log(Buffer.isBuffer(buffer1));
console.log(buffer1.length);
const bufferSrc = new Buffer( 'ABC' );
const bufferDest = Buffer.alloc(3);
bufferSrc.copy(bufferDest);
const Data = bufferDest.toString( 'utf-8' );
console.log(Data);
const bufferOld = new Buffer( 'GeeksForGeeks' );
const bufferNew = bufferOld.slice(0, 4);
console.log(bufferNew.toString());
const bufferOne = new Buffer( 'Happy Learning ' );
const bufferTwo = new Buffer( 'With GFG' );
const bufferThree = Buffer.concat([bufferOne, bufferTwo]);
console.log(bufferThree.toString());
|
Run the index.js file using the following command:
node index.js
Output:
Happy Learning
true
100
ABC
Geek
Happy Learning With GFG
Reference: https://nodejs.org/api/buffer.html
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...