Last active
September 13, 2022 15:39
-
-
Save gagan-bansal/28236dc60d664467917649c9d82909c7 to your computer and use it in GitHub Desktop.
Node.js stream transform example to fitler the data and having delay in transform function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const {Transform} = require('stream'); | |
const split = require('split'); | |
const readStream = fs.createReadStream('./numbers'); | |
const writeStream = fs.createWriteStream('./evens'); | |
function test (chunk, cb) { | |
const val = parseInt(chunk.toString()); | |
if (val % 2 === 0) cb(null, val.toString() + '\n'); | |
else cb(); | |
} | |
class Filter extends Transform { | |
_transform(chunk, encoding, cb) { | |
setTimeout(() => { | |
test(chunk, cb); | |
}, Math.random() * 10); | |
} | |
} | |
const filter = new Filter(); | |
readStream.pipe(split()).pipe(filter).pipe(writeStream); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment