Introduction to Node.js Streams
This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.
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.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based Node.js courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for Node.js books — check the publication year so the examples match current versions.
Search Amazon →