From 227fbe844b13a8014f4419e88cf0fc86bb4a7ad7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=89=E5=92=B2=E6=99=BA=E5=AD=90?= Date: Sat, 17 Sep 2022 15:23:13 +0800 Subject: [PATCH] fix: cannot find eof --- src/ts-errs-map.ts | 2 +- src/utils.ts | 13 ++++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/ts-errs-map.ts b/src/ts-errs-map.ts index 500481a..4d3fad8 100644 --- a/src/ts-errs-map.ts +++ b/src/ts-errs-map.ts @@ -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} diff --git a/src/utils.ts b/src/utils.ts index b0ba0de..0d8112f 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -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}'.` ) } @@ -37,14 +37,15 @@ export function getLineByIndexesFromFile( lineIndexes: number[] ) { return new Promise((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() @@ -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,