advanced#Node.js#streams
Introduction to Node.js Streams
Learn the basics of Node.js streams and how to use them to handle large amounts of data.
Introduction to Streams
In Node.js, a stream is an abstract interface for handling streaming data. Streams are a way to handle large amounts of data in a continuous flow.
Step 1: Create a Readable Stream
Create a readable stream using the fs module.
const fs = require('fs');
const readableStream = fs.createReadStream('largefile.txt');
Step 2: Create a Writable Stream
Create a writable stream using the fs module.
const writableStream = fs.createWriteStream('output.txt');
Step 3: Pipe the Streams
Pipe the readable stream to the writable stream.
readableStream.pipe(writableStream);
Step 4: Handle Stream Events
Handle stream events, such as data and end.
readableStream.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data`);
});
readableStream.on('end', () => {
console.log('End of stream');
});
Step 5: Run the Code
Run the code to see the streams in action.
node streams.js
This will create a new file called output.txt with the contents of largefile.txt.