Skip to content

Commit 88b6af7

Browse files
committed
feat: Add loadTSVGZ() function
1 parent f4eb327 commit 88b6af7

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

src/files/tsv.ts

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ async function loadColumns(
1212
reader: ReadableStreamDefaultReader<string>,
1313
headers: string[],
1414
maxRows: number,
15+
startRow: number = 0,
1516
): Promise<ColumnsMap> {
1617
// Initialize columns in array for construction efficiency
1718
const initialCapacity = maxRows >= 0 ? maxRows : 1000
@@ -27,12 +28,12 @@ async function loadColumns(
2728
if (!value) {
2829
const nextRow = await reader.read()
2930
if (nextRow.done) break
30-
throw { code: 'TSV_EMPTY_LINE', line: rowIndex + 2 }
31+
throw { code: 'TSV_EMPTY_LINE', line: rowIndex + startRow + 1 }
3132
}
3233

3334
const values = value.split('\t')
3435
if (values.length !== headers.length) {
35-
throw { code: 'TSV_EQUAL_ROWS', line: rowIndex + 2 }
36+
throw { code: 'TSV_EQUAL_ROWS', line: rowIndex + startRow + 1 }
3637
}
3738
columns.forEach((column, columnIndex) => {
3839
// Double array size if we exceed the current capacity
@@ -49,6 +50,30 @@ async function loadColumns(
4950
)
5051
}
5152

53+
export async function loadTSVGZ(
54+
file: BIDSFile,
55+
headers: string[],
56+
maxRows: number = -1,
57+
): Promise<ColumnsMap> {
58+
const reader = file.stream
59+
.pipeThrough(new DecompressionStream('gzip'))
60+
.pipeThrough(createUTF8Stream())
61+
.pipeThrough(new TextLineStream())
62+
.getReader()
63+
64+
try {
65+
return await loadColumns(reader, headers, maxRows)
66+
} catch (e: any) {
67+
// Cancel the reader if we interrupted the read
68+
// Cancelling for I/O errors will just re-trigger the error
69+
if (e.code) {
70+
await reader.cancel()
71+
throw e
72+
}
73+
throw { code: 'INVALID_GZIP', location: file.path }
74+
}
75+
}
76+
5277
async function _loadTSV(file: BIDSFile, maxRows: number = -1): Promise<ColumnsMap> {
5378
const reader = file.stream
5479
.pipeThrough(createUTF8Stream())
@@ -67,7 +92,7 @@ async function _loadTSV(file: BIDSFile, maxRows: number = -1): Promise<ColumnsMa
6792
}
6893
}
6994

70-
return await loadColumns(reader, headers, maxRows)
95+
return await loadColumns(reader, headers, maxRows, 1)
7196
} finally {
7297
await reader.cancel()
7398
}

0 commit comments

Comments
 (0)