Skip to content

Commit

Permalink
fix: cannot find eof
Browse files Browse the repository at this point in the history
  • Loading branch information
sxzz committed Sep 17, 2022
1 parent c85ae99 commit 227fbe8
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/ts-errs-map.ts
Expand Up @@ -25,7 +25,7 @@ async function getErrPreviewLineByIndexFromFile(
// line index is zero-based, so we need to minus 1
const [prevLine, lineContent, nextLine] = await getLineByIndexesFromFile(
filePath,
[line - 1 - 1, line - 1, line - 1 + 1]
[line - 1, line, line + 1]
)
return `${errMsg}
Expand Down
13 changes: 8 additions & 5 deletions src/utils.ts
Expand Up @@ -28,7 +28,7 @@ export function isFilePath(absPath: string) {

function createOutOfRangeError(filePath: string, lineIndex: number) {
return new RangeError(
`Line with index ${lineIndex} does not exist in '${filePath}'. Note that line indexing is zero-based`
`Line with index ${lineIndex} does not exist in '${filePath}'.`
)
}

Expand All @@ -37,14 +37,15 @@ export function getLineByIndexesFromFile(
lineIndexes: number[]
) {
return new Promise<string[]>((resolve, reject) => {
if (lineIndexes.some((lineIndex) => lineIndex < 0 || lineIndex % 1 !== 0))
if (lineIndexes.some((lineIndex) => lineIndex <= 0 || lineIndex % 1 !== 0))
return reject(new RangeError(`Invalid line number`))

let cursor = 0
let cursor = 1
const input = fs.createReadStream(filePath)
const rl = readline.createInterface({ input })
const linesCollect: string[] = []
rl.on('line', (line) => {

function read(line: string) {
if (cursor === Math.max(...lineIndexes)) {
// the last index
rl.close()
Expand All @@ -54,11 +55,13 @@ export function getLineByIndexesFromFile(
linesCollect.push(line)
}
cursor++
})
}

rl.on('line', (line) => read(line))
rl.on('error', reject)

input.on('end', () => {
read('')
reject(
createOutOfRangeError(
filePath,
Expand Down

0 comments on commit 227fbe8

Please sign in to comment.