UNPKG

text-stream-search

Version:

Searches for occurrences of a given search term in Node.js text streams

63 lines (62 loc) 2.69 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; const debug_1 = __importDefault(require("debug")); const text_stream_accumulator_1 = __importDefault(require("text-stream-accumulator")); const regex_search_1 = __importDefault(require("./searchers/regex-search")); const string_search_1 = __importDefault(require("./searchers/string-search")); const debug = debug_1.default("text-stream-search"); class TextStreamSearch { constructor(stream) { this.searches = []; stream.on("data", this.onStreamData.bind(this)); this.accumulator = new text_stream_accumulator_1.default(stream); } // Returns the full text received from the stream so far fullText() { return this.accumulator.toString(); } reset() { this.accumulator.reset(); } // Returns a promise that resolves when the given text shows up in the observed stream async waitForText(query, timeout) { debug(`adding subscription for '${query}'`); return new Promise(async (resolve, reject) => { const search = new string_search_1.default(query, this.accumulator, resolve, reject, timeout); this.searches.push(search); await this.checkSearches(); }); } // Calls the given handler when the given text shows up in the output waitForRegex(query, timeout) { debug(`adding text search for: ${query.toString()}`); return new Promise((resolve, reject) => { const search = new regex_search_1.default(query, this.accumulator, resolve, reject, timeout); this.searches.push(search); this.checkSearches(); }); } // Called when new text arrives onStreamData(data) { debug(`receiving text: '${data}'`); // need to wait for the next tick to give the accumulator time to update process.nextTick(() => { this.checkSearches(); }); } // Looks for new matches in the received text. // Called each time the text or search terms change. async checkSearches() { debug(`checking ${this.searches.length} subscriptions`); const text = this.fullText(); for (const search of this.searches) { await search.check(text); } } } /* Add compatibility with `import TextStreamSearch from '...'` */ Object.defineProperty(TextStreamSearch, "__esModule", { value: true }); Object.defineProperty(TextStreamSearch, "default", { value: TextStreamSearch }); module.exports = TextStreamSearch;