UNPKG

@stream-toolbox/replace

Version:

Replace the given Buffer in a readable stream with another Buffer.

52 lines (51 loc) 2 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var stream_1 = require("stream"); var StreamSearch = require("@stream-toolbox/search"); var StreamReplace = (function (_super) { __extends(StreamReplace, _super); function StreamReplace(find, replace, limit) { var _this = _super.call(this) || this; if (typeof find === "string") { find = Buffer.from(find, "utf-8"); } if (typeof replace === "string") { replace = Buffer.from(replace, "utf-8"); } _this.searcher = new StreamSearch({ needle: find, limit: limit, abandon: false }, function (isMatch, chunk) { if (isMatch) { _this.push(replace); } if (chunk.length) { _this.push(chunk); } }); return _this; } StreamReplace.prototype._transform = function (chunk, encoding, callback) { this.searcher.push(chunk); callback(null); }; StreamReplace.prototype._flush = function (callback) { this.searcher.flush(); callback(null); }; return StreamReplace; }(stream_1.Transform)); module.exports = function createReplace(find, replace, limit) { return new StreamReplace(find, replace, limit); };