Introduction to Minipass
Minipass is a powerful Node.js library that combines the best properties of Node.js streams and promises. It enables developers to handle streaming data efficiently with a simple and intuitive API. In this guide, we’ll walk through the core functionalities of Minipass and showcase dozens of useful API examples, followed by an application example demonstrating their practical use.
Core API Examples
Creating a Minipass Stream
const Minipass = require('minipass'); const myStream = new Minipass();
Writing to a Stream
myStream.write('Hello, '); myStream.write('world!'); myStream.end();
Reading from a Stream
myStream.on('data', (chunk) => { console.log(chunk.toString()); }); myStream.on('end', () => { console.log('Stream ended.'); });
Piping Streams
const readStream = new Minipass(); const writeStream = new Minipass(); readStream.pipe(writeStream); writeStream.on('data', (chunk) => { console.log(chunk.toString()); }); readStream.write('Piped data!'); readStream.end();
Handling Errors
myStream.on('error', (error) => { console.error('Error:', error.message); }); myStream.emit('error', new Error('Something went wrong'));
Application Example Using Minipass
Let’s create a simple application that reads data from one stream, processes it, and writes the processed data to another stream.
App Example: Uppercase Transformation
const Minipass = require('minipass'); const readStream = new Minipass(); const transformStream = new Minipass({ objectMode: true }); // Transform stream to convert chunks to uppercase transformStream.write = function(chunk) { this.emit('data', chunk.toString().toUpperCase()); }; const writeStream = new Minipass(); writeStream.on('data', (chunk) => { console.log('Processed Data:', chunk.toString()); }); readStream.pipe(transformStream).pipe(writeStream); readStream.write('hello '); readStream.write('world'); readStream.end();
This example demonstrates how Minipass can be used to seamlessly connect multiple streams and apply transformations on streaming data.
Hash: d45225d2ecf644e94e81b472eb82271d91de725c51f30a289dd2131c7370f35b