In a more perfect world, node.js would include this in its fs
functions.
I am familiar with the node.js filesystem documentatation. I’m also familiar with the readLines
method of fs
. Sadly, I find no readLinesSync
function in the above node.js filesystem documentation — that’s very close to what I’m looking for.
I need a Javascript function that reads and answers specified lines from
potentially large files. Since the files I’m reading might have thousands of
lines of text, I do not want read the entire file at once.
I’m implementing a server-side REST API using node.js running on a robust AWS
EC2 instance running Rocky Linux. I have full control over the platform.
I’m lost in the complexity of async
/await
, promises, and so on.
Here is the definition of the function I want to implement:
function readLinesSync(path, options) {
const lines = doWhateverItTakes()
return lines
}
The arguments to the above readLinesSync
are as follows:
-
@path
: The full absolute path of a possibly large text file. A typical value is'/home/tms/example_documents/example_1.txt'
-
@options
: A literal object containing at least the following bindings:-
@startLineIndex
: The zero-origin index of a line in the text file. A typical value is42
-
@stopLineIndex
: The zero-origin index of a line in the text file. A typical value is142
-
When readLinesSync
is called with the above typical values, I expect it to answer an array containing 100 lines of text read from the specified file, starting at line 42.
Importantly, this function must not return until the necessary file I/O is complete. Any complexity involving async
/await
or promises must be somehow encapsulated elsewhere.
Ideally, it will somehow catch and report any errors thrown along the way.
The project uses import ...
rather than require ...
.
I’m familiar with a stackoverflow related question. Sadly, the answer to that question only emits lines to the console. This is unresponsive to the most challenging aspect of my question.
In the most general case, I seek a pattern for encapsulating async
behavior
behind a synchronous wrapper.