@dwesley/linereader
Version:
A simple `Readliner` class, similar to Java's `readline()` method, written in typescript (for Node) to read files line-by-line asynchronously and quickly.
65 lines (64 loc) • 2.21 kB
JavaScript
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
// src/main.ts
import fs from "node:fs";
import readline from "node:readline";
var LineReader = class _LineReader {
static {
__name(this, "LineReader");
}
/**
* Creates a readline interface for reading a file.
*
* @param {fs.PathLike} path - The path of the file to read.
* @param {BufferEncoding} [encoding=utf8] - The encoding of the file. Defaults to "utf8".
* @return {readline.Interface} The readline interface for reading the file.
*/
static createReadLineInterface(path, encoding = "utf8") {
return readline.createInterface({
input: fs.createReadStream(path, {
encoding,
flags: "r",
emitClose: true,
autoClose: true
}),
crlfDelay: Infinity,
terminal: false
});
}
/**
* Creates a LineReader object for reading lines from a file.
*
* @param {fs.PathLike} path - The path of the file to read.
* @param {BufferEncoding} encoding - The encoding to use when reading the file. Default is "utf8".
* @return {Object} An object with methods for reading lines from the file.
* - `hasNextLine`: A function that returns `true` if there is another line to read, `false` otherwise.
* - `nextLine`: An async function that reads the next line from the file and returns it.
* - `close`: A function that closes the LineReader and stops reading lines from the file.
*/
static create(path, encoding = "utf8") {
let EOF = false;
const RLI = _LineReader.createReadLineInterface(path, encoding);
async function nextLine(fn) {
if (EOF)
return void 0;
const line = await RLI[Symbol.asyncIterator]().next();
const value = line.value;
return typeof fn === "function" ? fn(value) : value;
}
__name(nextLine, "nextLine");
RLI.once("close", () => {
EOF = true;
});
return {
hasNextLine: () => !EOF,
nextLine,
/** Manually closes the LineReader by calling the `close` method */
close: () => RLI.close()
};
}
};
export {
LineReader
};
//# sourceMappingURL=main.js.map