NA +91-8727899942 thecoderjob@gmail.com

CHAPTER - 25

Concept of streams and buffers in node js

In Node.js, streams and buffers are fundamental concepts used for handling data, especially when working with I/O operations. They provide efficient ways to read and write data, allowing you to process large amounts of data without consuming a lot of memory.

Buffers : A buffer is a temporary storage area in memory used to store raw binary data. It is essentially an array of integers, which corresponds to raw bytes of data.

Streams : Streams allow you to read or write data piece by piece without loading the entire data into memory.

Types of Streams : 

  1. Readable - Used for reading data
  2. Writable - Used for writing data
  3. Duplex - Used for both reading and writing
  4. Transform - A type of duplex stream where the output is computed based on the input

Here's is the Code !!

//Creating Buffers
const buf = Buffer.alloc(10); // creates a buffer of size 10 bytes initialized with zeros
const buf = Buffer.from('Hello, World!');

//You can read from and write to buffers using various methods:
const buf = Buffer.alloc(10);
// Write to buffer
buf.write('Hello');
// Read from buffer
console.log(buf.toString()); // Outputs: Hello

//Reading from a Readable Stream
const fs = require('fs');

const readableStream = fs.createReadStream('input.txt');

readableStream.on('data', (chunk) => {
  console.log(`Received ${chunk.length} bytes of data.`);
});

readableStream.on('end', () => {
  console.log('Finished reading data.');
});

readableStream.on('error', (error) => {
  console.error(`Error reading data: ${error}`);
});

//Writing to a Writable Stream
const fs = require('fs');

const writableStream = fs.createWriteStream('output.txt');

writableStream.write('Hello, World!
');
writableStream.write('Another line.');

writableStream.end();

writableStream.on('finish', () => {
  console.log('Finished writing data.');
});

writableStream.on('error', (error) => {
  console.error(`Error writing data: ${error}`);
});

Chapter 24

Caching strategies in node Js

Previous chapter

Chapter 26

How to add clustering in Node Js

Next chapter

Get In Touch

NA

thecoderjob@gmail.com

+91-8727899942

Popular Links

© www.thecoderjob.com. All Rights Reserved.               Designed by HTML Codex