Created
May 30, 2020 09:50
-
-
Save kumarasinghe/6ee58dd03b7388466c376327883221cc to your computer and use it in GitHub Desktop.
NodeJS : Reading a part of a file bottom to up and return the lines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
reads a file upwards from the given 'startPosition' to the specified length and | |
returns an object with the lines and the final position read | |
if 'startPosition' is not specified it will be the very bottom of the file | |
*/ | |
async function readFileBottomUp(filename, length, startPosition) { | |
return new Promise((resolve, reject) => { | |
// file does not exist | |
if (!fs.existsSync(filename)) { | |
reject(new Error(`File ${filename} does not exist.`)) | |
return | |
} | |
// calculate boundaries to read | |
let endPosition = (startPosition > -1) ? startPosition : fs.statSync(filename).size - 1 | |
startPosition = endPosition - length | |
// read the chunk | |
let buffer = '' | |
let fileStream = fs.createReadStream( | |
filename, | |
{ | |
'start': startPosition, | |
'end': endPosition, | |
'encoding': 'utf8' | |
} | |
) | |
fileStream.on('readable', () => { | |
let data = fileStream.read() | |
// data chunk available => add to buffer | |
if (data) { | |
buffer += data | |
} | |
// end of stream => process buffer | |
else { | |
let firstLineStart = buffer.indexOf('\n') + 1 | |
let lastLineEnd = (endPosition == fs.statSync(filename).size - 1) ? buffer.length : buffer.lastIndexOf('\n') | |
let lines = buffer.substring(firstLineStart, lastLineEnd) | |
resolve({ 'lines': lines, 'endByte': startPosition + firstLineStart }) | |
} | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment