Introduction to `is-stream`
The `is-stream` module is an invaluable tool in the realm of Node.js for determining object types, particularly streams. This lightweight module provides developers with a seamless way to identify streams and handle various stream types effectively.
API Examples
1. Installation
npm install is-stream
2. Basic Usage
Here is how you can use the `is-stream` module to check if an object is a stream:
const isStream = require('is-stream'); const stream = require('stream'); console.log(isStream(new stream.Readable())); // true console.log(isStream({})); // false
3. Checking Different Stream Types
isStream.readable
console.log(isStream.readable(new stream.Readable())); // true console.log(isStream.readable(new stream.Writable())); // false
isStream.writable
console.log(isStream.writable(new stream.Writable())); // true console.log(isStream.writable(new stream.Duplex())); // true
isStream.duplex
console.log(isStream.duplex(new stream.Duplex())); // true console.log(isStream.duplex(new stream.Transform())); // true
isStream.transform
console.log(isStream.transform(new stream.Transform())); // true
4. Real-World Application Example
Suppose you are building a file processing application. You can use `is-stream` to check the type of stream and proceed accordingly:
const fs = require('fs'); const isStream = require('is-stream'); const stream = require('stream'); const readStream = fs.createReadStream('source.txt'); const writeStream = fs.createWriteStream('destination.txt'); if (isStream(readStream) && isStream.writable(writeStream)) { readStream.pipe(writeStream); } else { console.error('Error: One of the provided streams is not valid.'); }
This simple application reads a file (‘source.txt’) and writes its content to another file (‘destination.txt’). The `is-stream` module ensures that both the read and write streams are valid before proceeding.
In summary, `is-stream` is a powerful utility that can significantly enhance your Node.js application’s resilience by accurately identifying different types of streams.
Hash: 73d56d960864c3d853381391b43ba491d658a719f03ba10c61c5685acc5511cd