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 :
//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}`);
});
© www.thecoderjob.com. All Rights Reserved. Designed by HTML Codex