@naturalcycles/nodejs-lib
Version:
Standard library for Node.js
31 lines (30 loc) • 914 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformTap = void 0;
const stream_1 = require("stream");
/**
* Similar to RxJS `tap` - allows to run a function for each stream item, without affecting the result.
* Item is passed through to the output.
*
* Can also act as a counter, since `index` is passed to `fn`
*/
function transformTap(fn, opt = {}) {
const { logger = console } = opt;
let index = -1;
return new stream_1.Transform({
objectMode: true,
...opt,
async transform(chunk, _, cb) {
// console.log('tap', chunk)
try {
await fn(chunk, ++index);
}
catch (err) {
logger.error(err);
// suppressed error
}
cb(null, chunk); // pass through the item
},
});
}
exports.transformTap = transformTap;