import fs from "node:fs"; import readline from "node:readline/promises"; import { tokenize } from "./tokenizer.js"; import { LocalFile } from "@entity-access/server-pages/dist/core/LocalFile.js"; export default abstract class LineReader { static create(source: string | LocalFile): LineReader { if (typeof source === "string") { return new StringLineReader(source); } return FileLineReader.create(source.path); } abstract readLines(): AsyncGenerator; abstract [Symbol.dispose](); } class StringLineReader implements LineReader { constructor(private text: string) { // do nothing.. } async *readLines() { for(const line of tokenize(this.text, "\n")) { if (line.endsWith("\r")) { yield line.substring(0, line.length-1); continue; } yield line; } } [Symbol.dispose]() { // do nothing... } } class FileLineReader implements LineReader { public static create(filePath: string) { return new FileLineReader(filePath); } reader: readline.Interface; constructor(filePath: string) { const input = fs.createReadStream(filePath); this.reader = readline.createInterface({ input, crlfDelay: Infinity}); } public async * readLines() { for await(const line of this.reader) { yield line; } } [Symbol.dispose]() { this.reader.close(); } }