Skip to content

Instantly share code, notes, and snippets.

@gagan-bansal
Last active September 13, 2022 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gagan-bansal/28236dc60d664467917649c9d82909c7 to your computer and use it in GitHub Desktop.
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.
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