Search This Blog

2023/09/28

Node.js:Buffer Interview Questions

 What is a Node.js Buffer?


A Node.js Buffer is a built-in object in Node.js used to
represent binary data directly in memory. It is a raw memory
allocation outside the JavaScript heap that allows Node.js to
handle binary data efficiently, which is crucial for tasks like
working with files, network streams, and other data sources
where binary data is involved.

How can you create a Buffer in Node.js?

You can create a Buffer in Node.js using one of the following methods:

Buffer.from(data): Creates a Buffer from an array, array-like object, or string.
Buffer.alloc(size): Allocates a new, zero-filled Buffer of the specified size.
Buffer.allocUnsafe(size): Allocates a new Buffer of the specified size, but it
may contain uninitialized memory.
Buffer.allocUnsafeSlow(size): Similar to Buffer.allocUnsafe(size), but slower.

How do you read data from a Buffer?

You can read data from a Buffer using methods like readUInt8,
readUInt16LE, readUInt16BE, readUInt32LE, readUInt32BE,
and similar methods for different data types. For example:

const buffer = Buffer.from([0x01, 0x02, 0x03, 0x04]);
const value = buffer.readUInt16LE(0); // Read a 16-bit integer in little-endian format from offset 0

How do you write data to a Buffer?

You can write data to a Buffer using methods like writeUInt8,
writeUInt16LE, writeUInt16BE, writeUInt32LE, writeUInt32BE,
and similar methods for different data types. For example:

const buffer = Buffer.alloc(4);
buffer.writeUInt16LE(0x0102, 0); // Write a 16-bit integer in little-endian format to offset 0


What are the differences between Buffer.from and Buffer.alloc?

Buffer.from creates a new Buffer and initializes it with the provided data (e.g., an array or string).
Buffer.alloc creates a new Buffer and initializes it with zeros.
Buffer.from is used when you want to create a Buffer from existing data,
whereas Buffer.alloc is used when you want to create an empty Buffer with a specific size.

How can you convert a Buffer to a string in Node.js?

Answer: You can convert a Buffer to a string in Node.js using the toString method. For example:

const buffer = Buffer.from('Hello, World!');
const str = buffer.toString('utf8'); // Convert the Buffer to a UTF-8 encoded string


What is the purpose of Buffer.allocUnsafe and Buffer.allocUnsafeSlow?

Answer:

Buffer.allocUnsafe allocates a new Buffer of the specified size but does not initialize its contents.
It is faster than Buffer.alloc because it doesn't fill the buffer with zeros,
but you should be careful when using it as the buffer may contain random data.

Buffer.allocUnsafeSlow is similar to Buffer.allocUnsafe, but it may be slower
and should be used only in cases where Buffer.allocUnsafe is not available.

How can you check the length of a Buffer?

Answer: You can check the length of a Buffer using the length property or the byteLength method:

const buffer = Buffer.from('Hello');
const length1 = buffer.length; // 5
const length2 = buffer.byteLength; // 5

Node.js:Buffers in node.js

 create buffer from string


var buf = Buffer.from('abc');
console.log(buf.toString());


create empty buffer of length 15

var buf = Buffer.alloc(15);
console.log(buf);

return size of buffer

var buf = Buffer.from('abc');
console.log(buf.length);


join three buffer object to one

var buf1 = Buffer.from('a');
var buf2 = Buffer.from('b');
var buf3 = Buffer.from('c');
var arr = [buf1, buf2, buf3];

var buf = Buffer.concat(arr);
console.log(buf.toString());


A Buffer cannot be resized.

Max Buffer size :

var buffer = require('buffer')
console.log(buffer.constants.MAX_LENGTH)

it is less on 32 bit machine & more on 64 bit machines.

Checking wheather object is buffer

var buf1 = Buffer.from('a');
var buf2 = "sa"
console.log(Buffer.isBuffer(buf1));
console.log(Buffer.isBuffer(buf2));


Return the number of bytes in the string "abc":

var len3 = Buffer.byteLength('abc');
console.log(len3);


Check the length of a buffer object:

var buf = Buffer.alloc(15);
var len1 = Buffer.byteLength(buf);
var len2 = buf.length;
console.log(len1);
console.log(len2);


return index from where the searched value is starting. It returns -1 if the value is not present in the buffer.

const buffer = Buffer.from('GeeksforGeeks: A computer science portal');
const output = buffer.indexOf('computer');
console.log(output);

output:
17


const buffer = Buffer.from('geeks community');
const output = buffer.indexOf(101);
const output1 = buffer.indexOf('geeks community');
const output2 = buffer.indexOf('com',7);//start searching at position 7 starting from 0

console.log(output);
console.log(output1);
console.log(output2);

output:
0
1
-1

check if two buffers are equal

var buf1 = Buffer.from('Hi');
var buf2 = Buffer.from('Hi');
console.log(buf1.equals(buf2));

output:
true


subarray:

const buf = Buffer.from('GeeksforGeeks', 'ascii');
console.log("Original buffer is: " + buf);
cropped_buf = buf.subarray(5, 10);
console.log("Cropped buffer is: " + cropped_buf);
cropped_buf[0] = 70; // F
cropped_buf[1] = 79; // O
cropped_buf[2] = 82; // R
console.log("Cropped buffer after modification is: " + cropped_buf);
console.log("Original buffer after modification is: " + buf);

output:

Original buffer is: GeeksforGeeks
Cropped buffer is: forGe
Cropped buffer after modification is: FORGe
Original buffer after modification is: GeeksFORGeeks



another example with negative index

const buf = Buffer.from('GeeksforGeeks', 'ascii');
console.log("Original buffer is: " + buf);

cropped_buf = buf.subarray(-12, -1);
console.log("Cropped buffer is:" + cropped_buf);
cropped_buf = buf.subarray(-10, -5);
console.log("Cropped buffer is: " + cropped_buf);
cropped_buf = buf.subarray();
console.log("Cropped buffer is: " + cropped_buf);


output:
Original buffer is: GeeksforGeeks
Cropped buffer is:eeksforGeek
Cropped buffer is: ksfor
Cropped buffer is: GeeksforGeeks


include or not

const buffer = Buffer.from('Geek One');
console.log(buffer.includes('Geek'));

output:
true

another example
const buffer = Buffer.from('GeeksforGeeks: A computer science portal');
const output = buffer.includes('Geek', 15);
console.log(output);

output:
false


copy method:

let buffer2 = Buffer.from('for');
let buffer1 = Buffer.from('GeeksandGeeks');

buffer2.copy(buffer1, 5,0)
console.log(buffer1.toString());

output:
GeeksforGeeks


compare:
return 0,-1 or 1

const buffer1 = Buffer.from('Geek');
const buffer2 = Buffer.from('Geek');
const op = Buffer.compare(buffer1, buffer2);
console.log(op);

output:
0


sort buffer array:
const buffers = [
Buffer.from('A', 'utf8'),
Buffer.from('C', 'utf8'),
Buffer.from('B', 'utf8')
];

buffers.sort(Buffer.compare);


compare on buffer object

const buffer1 = Buffer.from('GeeksOne');
const buffer2 = Buffer.from('GeekTwo');
let op = buffer1.compare(buffer2, 4);
let op1 = buffer1.compare(buffer2, 0, 7, 5);
console.log(op);
console.log(op1);

output:
-1
1


another example:
const buffer1 = Buffer.from("Geeks");
const buffer2 = Buffer.from("GeeksFor");

let op1 = buffer1.compare(buffer2, 0, 5);
console.log(op1);

output:
0